Java 如何手动调用 Swing 中的 Action?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3079524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:16:23  来源:igfitidea点击:

How do I manually invoke an Action in swing?

javaswingaction

提问by exhuma

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:

在我的生活中,我似乎无法找到有关 Java Swing 操作的详细信息:'( 当我遇到它们时,我立即意识到它们的用处。到目前为止,这一切都很容易使用。现在我被一件小事困住了:如何我是手动运行它们吗?我的意思是代码?请注意,我正在使用 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");

( 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?

所以现在我有了对 Action 的有效引用。现在我该如何运行它?

采纳答案by akf

If you want to run your action manually, you can generate an ActionEventand pass it into the actionPerformedmethod that your Actionmust implement, as the Actioninterface extends ActionListener.

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

回答by trashgod

Because an Actionis an EventListener, you may want to consider implementing an EventListenerListas a way to expose methods that fire actions.

因为 anAction是 an EventListener,您可能需要考虑实现 anEventListenerList作为公开触发操作的方法的一种方式。

回答by b1nary.atr0phy

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