Java:ActionListener接口

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

效果图如下:

在这里插入图片描述

猜你喜欢

转载自www.cnblogs.com/000zwx000/p/12531697.html