Skip to content
Advertisement

Call itemStateChanged() only after user interaction

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.

Advertisement

Answer

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.
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement