一、前言
今天在使用Java Swing中的JButton的事件触发机制时遇到了许多问题,简单的了解了一下。
二、事件监听机制
下面用一张图分析事件监听的机制(图片来自网络):
三、代码分析
3.1 分析一
1.事件源注册监听器
JButton newButton = new JButton();
newButton.addActionLister(listener);
1
2
JButtonnewButton=newJButton();
newButton.addActionLister(listener);
2.用户触发事件
例如单击该按钮
3.创建事件对象即ActionEvent Object
ActionEvent e;
1
ActionEvente;
4.将事件的对象传递给监听器并调用监听器方法
@Override
public void actionPerformed(ActionEvent e) {
// 相应的逻辑判断
if(e.getSource()==jb)
{
this.dispose();
// 点击按钮时frame1销毁,new一个frame2
new frame2();
}
}
1
2
3
4
5
6
7
8
9
10
@Override
publicvoidactionPerformed(ActionEvente){
// 相应的逻辑判断
if(e.getSource()==jb)
{
this.dispose();
// 点击按钮时frame1销毁,new一个frame2
newframe2();
}
}
3.2 分析二
以上代码也可以这样设计:
JButton newButton = new JButton();
newButton.addActionLister(listener);
newButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jb)
{
this.dispose();
// 点击按钮时frame1销毁,new一个frame2
new frame2();
}
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
JButtonnewButton=newJButton();
newButton.addActionLister(listener);
newButton.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
if(e.getSource()==jb)
{
this.dispose();
// 点击按钮时frame1销毁,new一个frame2
newframe2();
}
});
}
四、代码实现
public static void main(String[] args) {
JFrame jf = new JFrame("事件监听测试");
jf.setVisible(true);
jf.setSize(100, 200);
JButton jb = new JButton("触发事件");
jf.add(jb);
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 进行逻辑处理即可
System.out.println("触发了事件");
}
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
publicstaticvoidmain(String[]args){
JFramejf=newJFrame("事件监听测试");
jf.setVisible(true);
jf.setSize(100,200);
JButtonjb=newJButton("触发事件");
jf.add(jb);
jb.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
// 进行逻辑处理即可
System.out.println("触发了事件");
}
});
}
五、详解actionListener()和actionPerformed()
5.1 actionListener()
actionListener()接口是Java中关于事件处理的一个接口,继承自EventListener。
5.2 actionPerformed()
actionPerformed()是actionListener()接口中声明的一个方法,在监听器接收到触发事件源时自动调用的,比如按下按钮后,它和KeyListener,MouseLisenter,WindowListener等是同一性质的方法(分别对应键盘监听、鼠标监听、窗口监听)。在这个方法中可以做相应的逻辑处理。