我正在尝试了解有关事件处理的更多信息,但无论我读到什么,它主要是关于如何使用它以便发生某些事情,而不是它如何工作。
到目前为止,我知道有两种方法可以在单击按钮时让事情发生。
Action 监听器:
myButton.addActionListener(new ActionListener() { @override actionPerformed... });
和抽象 Action :
public class MyAction extends AbstractAction {
public MyAction(String text, ImageIcon icon, String desc, Integer mnemonic) {
super(text, icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Action", e);
}
}
MyAction myAction = new MyAction(...);
myButton.setAction(myAction);
我知道我可以将我想要发生的一切写入actionPerfomed()
方法。
但由于我不知道,在后台究竟发生了什么,我无法判断一个是否比另一个有任何优势,或者我应该在哪种情况下使用哪个?
如果扩展 AbstractAction,则不能扩展任何其他类。无论如何,您可能希望尽可能避免使用子类。
我个人建议实现接口(interface) ActionListener
,然后在使用“this”关键字时将 Action 监听器添加到您的 swing 对象(或您监听的任何对象)。
public class ClassName implements ActionListener {
private JButton button = new JButton("click me");
public ClassName() {
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
//perform action
}
}
}
当然,您也可以直接添加 ActionListener
(通过使用 .addActionListener(new ActionListener() {});
,但是通过使用 this
,您可以将所有操作组合在一起。
//edit:另一种方法是使用 MouseListener
,它可以监听对您的对象的任何点击,因此您也可以使用像 JLabel
这样的 Swing 对象作为“buttons"- 但是,如果您使用 JButtons
,考虑到 ActionListener
更容易使用,并且您不必创建很多类,这将是不必要的努力(例如 mousePressed
、mouseClicked
、mouseReleased
等)。但是,如果您无论如何都需要 MouseListener
某处,您可能需要考虑使用它们,以便将所有事件组合在一起。
注意:我不知道 ActionListener
和 MouseListener
是否同样快,或者其中一种方法更好!如果您的程序已经需要很多功能,您可能想要使用 ActionListener
,如果这两种解决方案中的任何一种更快的话,我想这是更快的方法。