如何在swing中手动调用Action?

exh*_*uma 24 java 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");
Run Code Online (Sandbox Code Playgroud)

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

所以现在我有一个对Action的有效引用.现在我该如何运行它?

b1n*_*phy 31

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

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
    });
}
Run Code Online (Sandbox Code Playgroud)


akf*_*akf 10

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

  • 我再次遇到了这个问题,你的回答是 - 在我看来 - 比@ b1nary.atr0phy更详细.即使它有更多的赞成,我会保持这一点被接受.我想另一个吸引了更多的选票,因为它是复制/可粘贴的.也许代码示例会改善这个答案? (2认同)
  • 当然,代码示例会很方便 - 不支持复制/粘贴编程,但它会以程序员更容易理解的方式说明概念。 (2认同)