基础的ActionListener响应
来源:互联网 发布:苹果数据开关在哪 编辑:程序博客网 时间:2024/05/22 05:33
关于ActionListener的响应问题,就我的理解可以有两种方法。第一种就是你放到一个新的类里面,实现ActionListener接口,然后写好public void actionPerformed(ActionEvent e)的方法。这种当继承自JFrame还是蛮有用的,但是如果是一个在public static void main(String[] args)中建立一个JFrame,然后对里面的(比如按钮)实现监听,那么去实现ActionListener接口就不那么合适了(哎,很多都是当你做过后才知道什么是合适的),不过Java提供了另一种解决方案:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ActionListenerTest ...{
public static void main(String[] args) ...{
JFrame frame = new JFrame("Button Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton jbClose = new JButton("Close the Frame");
jbClose.addActionListener(new ActionListener () ...{
public void actionPerformed(ActionEvent e) ...{
if (e.getSource().equals(jbClose)) ...{
System.exit(0);
}
}
}
);
frame.add(jbClose);
frame.pack();
frame.setVisible(true);
}
}
也就是在addActionListener的参数中新定义到一个ActionListenner并重写它的actionPerformed。不过要注意的是,这个actionPerformed一定要是public的,不然权限不够。还有就是里面用到的组件在外部必须声明为final的,这点也许会造成些许使用的限制。
另一种其实是很常用的那种,前面也用到过,不过这里再写一遍好了,翻来翻去很麻烦的。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ButtonFrame extends JFrame implements ActionListener ...{
JButton jbClose = null;
public ButtonFrame() ...{
super("ButtonFrame Test");
jbClose = new JButton ("Close the Frame in ButtonFrame");
jbClose.addActionListener(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(jbClose);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) ...{
if (e.getSource().equals(jbClose)) ...{
System.exit(0);
}
}
public static void main(String[] args) ...{
ButtonFrame bf = new ButtonFrame();
}
}
两个程序的效果是一样的,都是点击了按钮后就结束程序。
- 基础的ActionListener响应
- Java学习笔记之SWING -- 基本SWING程序(基础的ActionListener响应)
- Swing中的ActionListener响应研究
- ActionListener的用法
- ActionListener接口--事件处理基础
- ActionListener
- windowListener和ActionListener的区别
- dispose();不是ActionListener的方法
- 用JavaScript调用JSF的Action, ActionListener
- JSF中action 和 actionListener的区别
- JSF中action 和actionListener的区别
- JSF中action 和actionListener的区别
- 关于Java swing Jcomponent的ActionListener
- ActionListener的三种实现方法
- ActionListener的三种实现方法
- ActionListener的三种实现方法
- JSF之Action 与ActionListener的区别
- ActionListener的三种实现方法
- 未与信任 SQL Server 连接相关联
- 高质量C++/C编程指南 -- 第2章 程序的版式
- 婚姻的不幸之处
- 细数3721(雅虎助手)两年来的流氓升级史
- 雅虎助手是如何自杀式攻击360安全卫士的
- 基础的ActionListener响应
- 看看如何开始~
- SQLServer2000 JDBC驱动的完整安装及测试说明
- 字符,字节和编码
- 在线写诗机器人
- Feel Good Inc
- 一个简单的EJB例子!!
- 高质量C++/C编程指南 -- 第3章 命名规则
- TABLE自动换行