简体   繁体   English

Java Swing:如何区分用户触发的事件?

[英]Java Swing: How to distinguish events triggered by user?

I'd like to update GUI elements ( JComboBox , JLabel , etc.) from code which shouldn't trigger change event. 我想从不应触发更改事件的代码中更新GUI元素( JComboBoxJLabel等)。 Is it possible to find out from java.awt.event.ActionEvent or java.awt.event.ItemEvent if the change was caused by an user or by running code like this? 是否可以从java.awt.event.ActionEventjava.awt.event.ItemEvent查找更改是否是由用户或通过运行此类代码引起的?

combo.setSelectedItem("my item")

The answer is: no. 答案是不。

But in some cases you can try to analyze the current InputEvent . 但是在某些情况下,您可以尝试分析当前的InputEvent To get it, use EventQueue.getCurrentEvent() . 要获取它,请使用EventQueue.getCurrentEvent() For example if user has triggered the change on clicking of another component, you can compare the component of the input event and the component of the action event (OK I know: it's unsafe. But in some cases it can help to avoid incrementing of application complexity). 例如,如果用户在单击另一个组件时触发了更改,则可以比较输入事件的组件和动作事件的组件(确定,我知道:这是不安全的。但是在某些情况下,它可以避免应用程序的增加复杂)。

For a button you can get the event modifiers: int buttonModifiers = evt.getModifiers(); 对于按钮,您可以获取事件修饰符: int buttonModifiers = evt.getModifiers(); If the button event was generated with a call to doClick() the modifier is 0, otherwise not. 如果按钮事件是通过调用doClick()生成的,则修饰符为0,否则为0。

By the way, you can find out such differences relatively easy by logging / printing using evt.toString() . 顺便说一句,您可以通过使用evt.toString()进行登录/打印来相对容易地找到这种差异。

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

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