28

For the life of me I cannot seem to find details on Java Swing Actions :'( When I came across them I immediately realised their usefulness. So far it's all been easy to work with. Now I'm stuck with one little thing: How do I run them manually? I mean by code? Note that I am building the GUI using Netbeans (if that makes any difference). I've come as far as:

Application a = Application.getInstance(JPADemoApp.class);
ApplicationContext ctx = a.getContext();
ActionMap am = ctx.getActionMap(JPADemoView.class, this.app);
Action act = am.get("fetchOrders");

( I wrote all on separate lines to simplify debugging )

So now I have a valid reference to the Action. Now how do I run it?

exhuma
  • 20,071
  • 12
  • 90
  • 123

3 Answers3

38

You can simply invoke the action event's method directly:

for(ActionListener a: buttonExample.getActionListeners()) {
    a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null) {
          //Nothing need go here, the actionPerformed method (with the
          //above arguments) will trigger the respective listener
    });
}
arkon
  • 2,209
  • 3
  • 27
  • 36
12

If you want to run your action manually, you can generate an ActionEvent and pass it into the actionPerformed method that your Action must implement, as the Action interface extends ActionListener.

akf
  • 38,619
  • 8
  • 86
  • 96
  • 2
    I came across this question again, and your answer is - in my opinion - more detailed than the one of @b1nary.atr0phy. Even though it has more upvotes, I will keep this one accepted. I guess the other one attracts more votes as it is copy/pasteable. Maybe a code-sample would improve this answer? – exhuma Jun 15 '15 at 13:08
  • 1
    Definitely, a code sample would be handy - not to support copy / paste programming, but it would illustrate the concept in a manner more understandable to a programmer. – Suma Jan 14 '16 at 11:17
2

Because an Action is an EventListener, you may want to consider implementing an EventListenerList as a way to expose methods that fire actions.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045