简体   繁体   English

Java Swing多个ActionListener

[英]Java Swing Multiple ActionListeners

I am trying to keep actions separate as possible but am coming across the problem of an action firing off before the other. 我试图使动作尽可能分开,但是遇到一个动作先于另一个触发的问题。 Right now I have a button that has two action listeners added. 现在,我有一个添加了两个动作侦听器的按钮。

JButton button = new JButton ();
...
button.addActionListener (new Action1 ());
button.addActionListener (new Action2 ());

2 is happening before 1. How can I guarantee the order? 2在1之前发生。如何保证订单? Is there a way to have an action that triggers other actions? 是否有一种方法可以触发其他操作?

Usually, event sources make no guarantees about the order in which listeners are notified. 通常,事件源不保证侦听器的通知顺序。 And that is for a reason: the pattern/concept is about decoupling the listener code, ie listeners should be independent of each other. 这是有原因的:模式/概念与解耦侦听器代码有关,即,侦听器应彼此独立。

If Action1 and Action2 really need to coordinate their work, the code should not be spread in two places. 如果Action1Action2真的需要协调工作,代码不应该在两个地方传播。

If the two actions are dependent in their order, then it is functionally one action. 如果这两个动作在顺序上是相互依赖的,那么从功能上讲它就是一个动作。 I would only register the first actionlistener and call the second one directly from within the first one or - even better - write the code in one single actionlistener. 我只会注册第一个动作侦听器,然后直接从第一个动作侦听器中调用第二个动作侦听器,或者-更好的是,在一个动作侦听器中编写代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM