java - addActionListener(this) 和 addActionListener(new ActionListener) 有什么区别?

标签 java event-handling actionlistener

我想向按钮添加事件处理 - 我注意到有两种方法可以做到这一点。

  1. 实现 ActionListener 接口(interface),然后将事件监听器附加到按钮。

示例:

countButton.addActionListener(this);

并且ActionPerformed方法中的将运行并显示结果。

  1. 不要实现 ActionListener 接口(interface),而是执行以下操作:

    countButton.addActionListener(new ActionListener() {
    
        public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            System.out.println("You clicked the button");
        }
    });  
    

第二种方法到底是如何工作的??????!!!

谢谢!

最佳答案

没有必要为第一种方法定义第二个类。您只需要添加
在类中使用 public void actionPerformed(ActionEvent e) 方法,并在让类实现 ActionListener 后执行您想要的操作。如果您愿意,您可以使用第二类,但这不是必需的。缺点是,如果您有多个 JButton,则需要使用长 if 语句指定事件源,以便采取适当的操作,即

第二种方法是向每个组件添加一个匿名内部 ActionListener。这是一种更加面向对象的方法,因为您可以更清晰地分离小部件的功能。在每个 actionPerformed 内部定义一个额外的方法是有利的,以便能够自由使用 this 并引用包含的类:

countButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        doCountButtonAction(e);
        // "this" here would refer to the ActionListener (not that useful)
    }
}); 

并实现该方法:

private void doCountButtonAction(ActionEvent e) {
   // do whatever you need to here
   // using "this" here refers to the containing class (i.e. JFrame, JPanel or whatever)
}

关于java - addActionListener(this) 和 addActionListener(new ActionListener) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7435622/

相关文章:

java - 一次搜索字符串中的多个字母

java - 使用MyBatis在Java中执行Filename.sql文件

java - ReentrantLock 与 CPU 级别同步?

c# - 手动调用EventHandler时出现无意义的错误消息

parameters - 如何在 PARAMETERS 语句自动生成的屏幕中检索字段的值?

Java 文件锁定

java - 使用 Vert.x for Java 的任何好的 Redis 客户端 API?

java - 我可以使用 BufferedReader 并在 actionListener 类中创建一个数组吗?

java - 使用屏幕键盘在 Java 中制作记事本,无法将其正确链接到文本区域

java - 如何使用 Action 监听器检查是否单击了某个按钮?