添加ActionListeners并在其他类中调用方法

我需要一些帮助,因为我非常喜欢。

我试图在这里制作的程序,曾经用于我的意图,但是当我试图使我的代码更具可读性时,我遇到了关于ActionListener的问题。

在我创建一个新类以使用所有方法之前,我使用了button.addActionListener(this); 它运作得很好。 既然我想把东西放在一个单独的课堂上,我完全不知道该怎么做。

所以我想我的问题是,如何让ActionListener在这样的情况下工作,或者我只是在这里做错了什么?

这是我认为相关的部分代码(大部分已编辑出来):

  //Class with frame, panels, labels, buttons, etc. class FemTreEnPlus { FemTreEnPlus() { //Components here! //Then to the part where I try to add these listeners cfg.addActionListener(); Exit.addActionListener(); New.addActionListener(); } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run(){ //Start the Program in the FemTreEnPlus Class new FemTreEnPlus(); } }); } 

那是带框架的类,这是另一个类,带有方法

 public class FemTreEnMethods extends FemTreEnPlus implements ActionListener { //Perform Actions! public void actionPerformed(ActionEvent ae){ if(ae.getSource() == cfgButton){ configureSettings(); } if(ae.getSource() == newButton){ newProject(); } if(ae.getSource() == exitButton){ exitProgram(); } } //All methods are down here 

在此先感谢您的帮助。

尽管教程的示例显示了以您的方式实现的侦听器的使用,但IMHO更有用的是使用匿名内部类来实现侦听器。 例如:

 cfgButton.addActionListener(new ActionListener() { @Override public void actionPerfomed(ActionEvent e) { // do the stuff related to cfgButton here } }; newButton.addActionListener(new ActionListener() { @Override public void actionPerfomed(ActionEvent e) { // do the stuff related to newButton here } }; exitButton.addActionListener(new ActionListener() { @Override public void actionPerfomed(ActionEvent e) { // do the stuff related to exitButton here } }; 

这种方法具有以下优点:

  • 听众逻辑很好地分开。
  • if块询问谁是事件的来源,则不需要嵌套。
  • 如果添加新按钮,则无需修改侦听器。 只需添加一个新的。

当然这取决于具体情况。 如果一组组件(例如单选按钮或复选框)的行为相同,那么只有一个侦听器并使用EventObject.getSource()来处理事件的源是有意义的。 这里提出了这种方法并在此举例说明。 注意这些示例也以这种方式使用匿名内部类:

 ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // do something here } };