Java:ActionListener接口
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java:ActionListener接口,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1624字,纯文字阅读大概需要3分钟。
内容图文
ActionListener动作事件监听器,当你在点击按钮时希望可以实现一个操作就得用到该接口了。
ActionListener接口所在包
ActionListener接口在event包中,即在开头引入该包。
import java.awt.event.*;
ActionListener接口使用方法
该接口只用实现一个方法叫做actionPerformed(ActionEvent arg0)这个方法。这个方法就是你希望触发事件时程序要做什么。
class ButtonListener/*这里你可以改名字*/ implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
/*content*/
}
}
但如果只写这一个ButtonListener类我们发现是无法在点击按钮时运行该方法的。呵呵,你还没有给按钮添加这个对象呢。记得要给按钮添加一个ActionListener的对象,即写如下代码。
ButtonListener button_listener = new ButtonListener();
button.addActionListener(button_listener);
接下来如果你又想移除该对象了,就直接remove掉就行了
button.removeActionListener(button_listener);
最后再唠叨一句,ActionListener接口不仅仅适用与点击按钮时触发事件,还可以在文本框、密码框按回车时触发事件等等。
代码
package technology;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFirstActionListener extends JFrame {
final static long serialVersionUID = 1L;
Container container = getContentPane();
JButton button = new JButton("点击我");
class ButtonListener implements ActionListener {
int x = 0;
public void actionPerformed(ActionEvent arg0) {
MyFirstActionListener.this.button.setText("我被点机了" + (++x) + "次");
}
}
public MyFirstActionListener()
{
super("JFrame窗体");
this.setBounds(200, 100, 200, 200);
button.addActionListener(new ButtonListener());
container.add(button);
this.setVisible(true);
}
public static void main(String[] args)
{
new MyFirstActionListener();
}
}
效果图如下:
内容总结
以上是互联网集市为您收集整理的Java:ActionListener接口全部内容,希望文章能够帮你解决Java:ActionListener接口所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。