Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically send ActionEvent to JButton?

How do I programmatically send an ActionEvent (eg button pressed/ACTION_PERFORMED) to a JButton?

I know of:

button.doClick(0);

and

button.getModel().setArmed(true);
button.getModel().setPressed(true);
button.getModel().setPressed(false);
button.getModel().setArmed(false);

But isn't it possible to directly send it an ActionEvent?

EDIT: This is not production code, it's just a little personal experiment.

like image 227
Anon Avatar asked Jan 20 '11 21:01

Anon


2 Answers

You can get a button's ActionListeners, and then call the actionPerformed method directly.

ActionEvent event;
long when;

when  = System.currentTimeMillis();
event = new ActionEvent(button, ActionEvent.ACTION_PERFORMED, "Anything", when, 0);

for (ActionListener listener : button.getActionListeners()) {
    listener.actionPerformed(event);
}
like image 151
jjnguy Avatar answered Oct 13 '22 19:10

jjnguy


Even if you could, why would you want to? Usually when people want to do something like this, it means they haven't properly separated the concerns of the UI from business logic. Typically they want to invoke some logic that occurs in an ActionListener without needing the action to take place.

public void actionPerformed(ActionEvent ae) {
    //SomeLogic
}

//...

public void someOtherPlace() {
    //I want to invoke SomeLogic from here though!
}

But really the solution is to extract that logic from the ActionListener and invoke it from both the ActionListener and that second location:

public void someLogic() {
    //SomeLogic
}

public void actionPerformed(ActionEvent ae) {
    someLogic();
}

//...

public void someOtherPlace() {
    someLogic();
}
like image 40
Mark Peters Avatar answered Oct 13 '22 18:10

Mark Peters