实现 java.awt.event.ActionListener
接口(interface)的最佳方法是什么?
让您的类实现 ActionListener 并将其添加为 ActionListener:
class Foo implements ActionListener{
public Foo() {
JButton button = new JButton();
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
}
}
或者添加一个匿名 ActionListener 类的对象:
class Foo{
public Foo() {
JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
}
最佳答案
有些人 (jeanette/kleopatra) 说几乎从不 使用 ActionListener,而是使用诸如 AbstractAction 之类的 Action。让你的 GUI 类实现你的监听器几乎总是一个糟糕的理想,因为这会破坏 Single Responsibility Principle并使您的代码更难维护和扩展,因此我强烈建议您不要这样做。
例如,一个内部类:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
class Foo {
public Foo() {
JButton button = new JButton(new ButtonAction("Action", KeyEvent.VK_A));
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name, Integer mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("button pressed");
}
}
}
关于java - 您的类应该实现 ActionListener 还是使用匿名 ActionListener 类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11438048/