为您的侦听器提供内部类使所有这些侦听器的目的非常明确。有时也可以避免很多检查,但要花更多的代码。
如果有面板
public class MyPanel extends JPanel implements ActionListener... button1.addActionListener(this); button2.addActionListener(this); checkbox1.addActionListener(this); timer3.addActionListener(this); public void actionPerformed(ActionEvent e) { if(e.getSource() == button1) else... ... //potentially many elses }很难确切地了解您的actionPerformed中发生了什么,因为它一次处理了许多不同的事件。有一个小组:
public class MyPanel extends JPanel... button1.addActionListener(new ButtonListener()); button2.addActionListener(new ButtonListener()); checkbox1.addActionListener(new CheckBoxListener()); timer3.addActionListener(new TimerListener()); private class TimerListener implements ActionListener { public void actionPerformed(ActionEvent e) { //do stuff related only to timers } }现在,如果您的计时器有问题,您可以轻松地确定有问题的班级。
更重要的是,它使您的代码更具可读性。如果其他人想在此类上工作,而他们需要使用计时器来修复事件处理,则不必搜索您的ifs即可找到具有计时器逻辑的零件。



