如何在Swing中手动调用一个Action?

28

我无法找到有关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 引用。那么我该如何运行它呢?

3个回答

38
你可以直接调用动作事件的方法:
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
    });
}

12

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


2
我又看到了这个问题,我认为你的答案比@b1nary.atr0phy更详细。尽管它获得了更多的赞,但我还是会接受这个答案。我猜其他的那个答案会吸引更多的投票,因为它可以复制和粘贴。也许增加代码示例会改善这个答案? - exhuma
1
毫无疑问,一个代码示例会很有用 - 不是为了支持复制/粘贴编程,而是它可以更加清晰地阐述概念,让程序员更易理解。 - Suma

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接