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
How do I manually invoke an Action in swing?
提问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 ActionEvent
and pass it into the actionPerformed
method that your Action
must implement, as the Action
interface extends ActionListener
.
如果您想手动运行您的操作,您可以生成一个ActionEvent
并将其传递到actionPerformed
您Action
必须实现的方法中,因为Action
接口扩展了ActionListener
。
回答by trashgod
Because an Action
is an EventListener
, you may want to consider implementing an EventListenerList
as 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
});
}