This is indeed a tale of two mysteries. I was mystified upon seeing why my JComboBox ItemListener’s itemStateChanged() event method gets fired twice. There was only one way to solve it and that was to Google for it.

And the answer? Two events are fired whenever you select an item in the JComboBox: the deselect event and the select event.

If you insist in using an ItemListener for this, you would have to place an if statement within the itemStateChanged() method to handle only select or deselect events.

Frankly, I would suggest you use an ActionListener instead.

Selecting a JComboBox item programmatically is pretty simple. Call either setSelectedIndex() or setSelectedItem() and that’s it. Problem is though, if you added an ItemListener to the JComboBox object, every time you do a select programmatically, the ItemStateChanged event method also gets affected.

Calling those two select methods from a JComboBox object is the most prone thing that developers do. However, if you do not want the ItemStateChanged method to be affected when you select an item programmatically, you can create a dummy variable inside theĀ ItemStateChanged method so that it would not get affected. Sad to say, that is the alternative aside from adding and removing the ItemListener.

Related Posts Plugin for WordPress, Blogger...