How do I manually invoke an Action in swing?

徘徊边缘 提交于 2019-12-28 16:31:37

问题


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?


回答1:


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.




回答2:


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
    });
}



回答3:


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



来源:https://stackoverflow.com/questions/3079524/how-do-i-manually-invoke-an-action-in-swing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!