简体   繁体   中英

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

combo.setSelectedItem("my item")

The answer is: no.

But in some cases you can try to analyze the current InputEvent . To get it, use 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(); If the button event was generated with a call to doClick() the modifier is 0, otherwise not.

By the way, you can find out such differences relatively easy by logging / printing using evt.toString() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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