2013-11-03 39 views
0

我一直在研究一个程序,而我的主类有大量的代码,它有超过20种不同的“addActionListener”方法。我怎样才能在单独的类中创建这个actionListener,itemStateChanged等等,但仍然像现在这样执行。任何提示将是最受欢迎的,因为我已经在这个类运行超过4000行代码:(谢谢如何在java中添加一个actionListener作为单独的类

+2

那么,我们应该提供的代码与您当前的代码的功能相同,不知道当前的代码?你的代码在哪里?你有什么尝试?面临的问题是什么? –

回答

1
class Mylistener implements ActionListener { 

    @Override 
    public void actionPerformed(ActionEvent e){ 
     if (e.getSource() == someButton){ 
      // do something 
     } else if (e.getSource() == someOtherButton){ 
      // do something 
     } 
     // add more else if statements for other components 
     // e.getSource() is the component that fires the event e.g. someButton 
    } 
} 

说你有两个按钮

JButton someButton = new JButton("SOME BUTTON"); 
JButton someOtherButton = new JButtton("SOME OTHER BUTTON"); 

ActionListener listener = new MyListener(); 

someButton.addActionListener(listener); 
someOtherButton.addActionListener(listener); 

编辑:

public MyClass extends JFrame { 

    JButton someButton = new JButton("SOME BUTTON"); 
    JButton someOtherButton = new JButtton("SOME OTHER BUTTON"); 

    public MyClass(){ 

     ActionListener listener = new MyListener(); 
     someButton.addActionListener(listener); 
     someOtherButton.addActionListener(listener); 
    } 

    class Mylistener implements ActionListener { 

    @Override 
    public void actionPerformed(ActionEvent e){ 
     if (e.getSource() == someButton){ 
      // do something 
     } else if (e.getSource() == someOtherButton){ 
      // do something 
     } 
     // add more else if statements for other components 
     // e.getSource() is the component that fires the event e.g. someButton 
    } 
} 
+0

这是行不通的,因为OP的目标是创建一个单独的类。因此这个类不会引用所有的按钮变量。当创建单独的类时,每个ActionListener应该只执行一个函数,因此您不需要知道函数,或者它是一个跨按钮的常用函数,那么您可以使用getSource()方法来了解生成该事件的组件。 – camickr

+0

这是对的,那么新的actionListener类如何执行知道变量都在主类中的方法呢? getSource()是什么意思? – Iron

+0

将MyListener作为原始类的内部类 –

3
public class MyActionListener implements ActionListener { 
    @Override 
    public void actionPerformed(ActionEvent evt) { 
     // actionPerformed here... 
    } 
} 

你会用它喜欢!

JButton button = new JButton(); 
button.addActionListener(new MyActionListener()); 

// OR 

MyActionListener listener = new MyActionListener(); 
JButton button = new JButton(); 
button.addActionListener(listener); 
+0

好吧,大家感谢大家的反馈意见。我会研究你提供的所有方法。谢谢 – Iron

相关问题