Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call itemStateChanged() only after user interaction

Tags:

java

swing

in my swing application I have a combo box with an ItemListener that does X if the user changes the value (via itemStateChanged()). However I also have a different function that changes the value of that combo box. In this case I do not want X to be done.

Is there a way to find out if the state change was caused by user interaction or from a function?

Thank you!

Edit: I used the flag method. Thanks for the quick answers. I just want to add, that itemStatechanged is actually called twice, once for deselection and once for selection. This needs to be dealt with otherwise the flag won't have any effect. The problem is discussed here.

like image 409
NiklasMM Avatar asked Dec 28 '22 01:12

NiklasMM


1 Answers

There are 2 ways to do the check:

  1. Define a flag isUser. The flag is true by default. Before changing programmatically set it to false and reset after setting the combo-box value. In the listener just check the flag and skip the action if necessary.
  2. Keep a reference to the listener and remove it before setting value, adding after.
like image 83
StanislavL Avatar answered Jan 05 '23 23:01

StanislavL