我想向按钮添加事件处理 - 我注意到有两种方法可以做到这一点。
- 实现 ActionListener 接口(interface),然后将事件监听器附加到按钮。
示例:
countButton.addActionListener(this);
并且ActionPerformed方法中的将运行并显示结果。
不要实现 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/