实现java.awt.event.ActionListener
接口的最佳方式是什么?
让您的类实现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) {
}
});
}
}
发布于 2012-07-12 01:27:13
那得看情况。如果您希望跨多个组件重用ActionListener
,则选择一个更好。如果ActionListener
只与一个按钮相关联,则可以选择第二个选项。
通常,如果您预期项目会有一些增长,您将创建一个单独的类(或内部类)。Foo
不需要实现ActionListener
。
https://stackoverflow.com/questions/11438048
复制相似问题