Reputation: 13
I am currently in a midst of developing an desktop application. I have the menu bar, which has the RUN command with the ALT-R mnemonic. Also, I have a RUN button in one of the frames & I have declared an ActionListener for the same. Is there a way to use the same ActionListener for the RUN command menu-item..? Or should it be re-declared all the way again..?
Upvotes: 1
Views: 5157
Reputation: 1932
Actually another option would be to use the ActionLister and set on up on the class that contains your buttons and other objects, or even use an ActionListener per UI widget and then just make calls out to the class that contains the logic. This seems a bit cleaner to me in terms of responsibility.
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.
}
}
This to me feels cleaner as it tries to keep UI and logic in separate classes. But it does depend too on what the "do something" is that you want to do.
Upvotes: 0
Reputation: 1389
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;
}
}
Here is way u can do
Upvotes: 0
Reputation: 114817
Consider storing all your listeners in a static map. Their logic has to be independent of any "outer class", for sure, because they have to run in any context:
public static Map<String, ActionListener> listeners = new HashMap<String, ActionListener>();
static {
listener.put("RUN", new ActionListener() {
// implementation of the "Run" actionlistener
});
// more listeners
}
and later on:
something.addActionListener(SomeManager.listeners.get("RUN"));
Upvotes: 2
Reputation: 59694
If you calling second class from first then you can pass the class where you implemented the ActionListener
to second class. i.e.
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
}
Or you can also easily pass it as:
class B{
//-- Where you want to add ActionListener
button.addActionListener(new A());
}
Upvotes: 0