java ActionListener 如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4885584/
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-10-30 08:28:09  来源:igfitidea点击:

How does an ActionListener work?

javaswingactionlistener

提问by aditya_gaur

I have an idea of how to use action listeners and implementing them but I was wondering if anyone could tell me how do they listen to the events? Is there some kind of polling mechanism?

我知道如何使用动作监听器并实现它们,但我想知道是否有人可以告诉我他们如何监听事件?是否有某种轮询机制?

回答by Joel

Action listeners register for Events using the Observer patternand they are notified, by the main event loop, of any events they are registered for. So no, it's not a polling (pull) mechanism, but the opposite - a (push) callback. This is an example of 'don't call us, we'll call you' programming. Because everything in your code runs off a single thread (the event loop) you don't have to worry about synchronizing between different events - so your code is threadsafe.

动作侦听器使用观察者模式注册事件,并通过主事件循环通知它们注册的任何事件。所以不,它不是轮询(拉)机制,而是相反的 - (推)回调。这是“不要打电话给我们,我们会打电话给你”编程的一个例子。因为代码中的所有内容都在单个线程(事件循环)上运行,所以您不必担心不同事件之间的同步 - 所以您的代码是线程安全的。

回答by AlexR

There is an event loop that is implemented into core of AWT. It receives all events and sends them to appropriate listeners.

有一个事件循环被实现到 AWT 的核心中。它接收所有事件并将它们发送到适当的侦听器。

回答by Harry Joy

The tutorial explains how they work fairly well: http://download.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

本教程解释了它们的工作原理:http: //download.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

I think the UI implementation of the JComponentwill fire (call) all registered events upon the user interacting with it (I think).

我认为 UI 实现JComponent将在用户与其交互时触发(调用)所有已注册的事件(我认为)。

For example, when a user clicks a JButton, the button (or it's ui, or some other internal handler) will lookup all registered ActionListenersand call their actionPerformed(...)methods.

例如,当用户单击 a 时JButton,按钮(或者它是 ui,或其他一些内部处理程序)将查找所有已注册的ActionListeners并调用它们的actionPerformed(...)方法。