Reputation: 2972
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.
Upvotes: 4
Views: 1363
Reputation: 123
I have the similar kind of situation where I need to differentiate two cases. Both options discussed here (flag and removal/addition of listener) do not work all the time, as the item listener is asynchronously called on EDT thread. However remove and adding the particular item listener is more safe . To further ensure that all the previous actions will be dealt before you add the item listener, I use fireEvents()
just before adding the listener again.
Upvotes: 0
Reputation: 57381
There are 2 ways to do the check:
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.Upvotes: 6
Reputation: 7943
From what I understand you could very easily sort out your problem using a flag.
Just make a boolean flag, e.g. isDoneByMethod
which will be on entrance to a method set to true
and at the end set to false
and between these two do the operation on the combobox. Then inside the itemStateChanged()
check for the value of the isDoneByMethod
flag and act accordingly.
Upvotes: 4