2011-04-21 58 views
1

我目前正在开发一个桌面应用程序。我有菜单栏,其中带有ALT-R助记符的RUN命令。此外,我有一个运行按钮在其中一个框架&我已经宣布一个ActionListener相同。有没有办法使用相同的ActionListener作为运行命令menu-item ..?还是应该再次重申声明..?如何在不同的类中使用动作侦听器?

+0

这些类是孤立的。此外,班级中使用的本地/私有变量会发生什么? – 2011-04-21 12:33:22

回答

0

如果您从第一堂课开始第二堂课,那么您可以将您实施ActionListener的班级转到第二堂课。即

class A implements ActionListener{ 
    @Override 
    public void actionPerformed(ActionEvent ae) { 
    //--- coding......... 
    } 

    //--- Somewhere in this class 
    B b=new B(this); 
} 

class B{ 
    A a; 
    public B(A a){ 
     this.a = a; 
    } 
    //-- now use this.a where you wanna set actionListener 
} 

或者你也可以很容易地把它作为:

class B{ 
    //-- Where you want to add ActionListener 
    button.addActionListener(new A()); 
} 
+0

i thnk dis是如何做到这一点的。我们不得不重新声明局部变量,全局都是类的......感谢支持..! – 2011-04-21 13:02:35

0
class ActionL implements ActionListener{ 
    // Here to override 
    public void actionhapp(ActionEvent ae) { 
    // do your code 
    } 


    BAction b=new BAction(this); 
} 

class BAction{ 
    ActionL a; 
    public BAction(A a){ 
     this.a = a; 
    } 


} 

这里是办法u能做到

+2

如果您复制我的答案,但至少更改名称正确.....不担心; ;-) – 2011-04-21 12:40:38

2

考虑存储在静态地图中的所有听众。他们的逻辑必须是独立于任何“外部类”,可以肯定的,因为他们必须在任何情况下运行:

public static Map<String, ActionListener> listeners = new HashMap<String, ActionListener>(); 
static { 
    listener.put("RUN", new ActionListener() { 
    // implementation of the "Run" actionlistener 
    }); 
    // more listeners 
} 

,稍后:

something.addActionListener(SomeManager.listeners.get("RUN")); 
0

其实另一种选择是使用ActionLister并在包含按钮和其他对象的类上进行设置,或者甚至使用每个UI小部件的ActionListener,然后仅向包含该逻辑的类发出调用。就责任而言,这对我来说似乎有点干净。

JButton myButton = new JButton("RUN"); 
myButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent ae) { 
     myLogicClass.executeRun(); 
    } 
}; 

public class MyLogicClass { 
    public void executeRun() { //or parms if you need it. 
     //do something in here for what you want to happen with your action listener. 
    } 
} 

这让我感觉更干净,因为它试图将UI和逻辑保持在不同的类中。但它也取决于你想做什么“做某事”。

相关问题