Java语言学习--Swing中Button事件监听

1 前言

今天在使用Java Swing中的JButton的事件触发机制时遇到了许多问题,简单的了解了一下。

2 事件监听机制

事件监听的机制如下图所示分析。

3 代码分析

3.1 分步解析

1.事件源注册监听器

JButton newButton = new JButton();
newButton.addActionLister(listener);

2.用户触发事件 例如单击该按钮 3.创建事件对象即ActionEvent Object

ActionEvent e;

4.将事件的对象传递给监听器并调用监听器方法

@Override
    public void actionPerformed(ActionEvent e) {
        // 相应的逻辑判断
        if(e.getSource()==jb)
        {
            this.dispose();
            // 点击按钮时frame1销毁,new一个frame2
            new frame2();
        }
    }

3.2 分析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();
	    }
	});
}

4 实例演示

例如,点击按钮,后台输出一句话。

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("触发了事件");
			}
		});

	}

5 详解actionListener()和actionPerformed()

  1. actionListener()接口 我们看一下Java API()中关于actionListener()接口的定义。
The listener interface for receiving action events. The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component’s addActionListener method. When the action event occurs, that object’s actionPerformed method is invoked.

简单点说,actionListener()接口是Java中关于事件处理的一个接口,继承自EventListener。

  1. actionPerformed()抽象方法 Java API中的定义: actionPerformed()是actionListener()接口中声明的一个抽象方法,在监听器接收到触发事件源时自动调用的,比如按下按钮后,它和KeyListener,MouseLisenter,WindowListener等是同一性质的方法(分别对应键盘监听、鼠标监听、窗口监听)。在这个方法中可以做相应的逻辑处理。
经验分享 程序员 微信小程序 职场和发展