如何在swing中手动调用Action?

对于我的生活,我似乎无法找到关于Java Swing Actions的详细信息:’(当我遇到它们时,我立即意识到它们的用处。到目前为止,这一切都很容易使用。现在我被困在一个小东西:如何我手动运行它们?我的意思是代码?注意我正在使用Netbeans构建GUI(如果这有任何区别)。我已经到了:

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

(我在单独的行上写了所有内容以简化调试)

所以现在我对Action有了一个有效的参考。 现在我该如何运行它?

如果要手动运行操作,可以生成ActionEvent并将其传递给Action必须实现的actionPerformed方法,因为Action接口扩展了ActionListener

您可以直接调用action事件的方法:

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

因为ActionEventListener ,所以您可能需要考虑实现EventListenerList作为公开触发操作的方法的方法。