Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JComboBox and ItemListener  RSS feed

Shlomo Shizgal
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was wondering if anyone could offer any suggestions with regard to the
following problem with a JComboBox.
What we are trying to do is as follows:
1) We have a JComboBox with an ItemListener added to it.
2) The user makes a selection from the JComboBox.
3) In the code that is run in response to the selection made by the user, a
dialog box is opened. Its purpose it to warn the user of implications of their
selection that they may not be aware of, and the user is asked if they want to
proceed anyways.
4) If they answer Yes, their new selection is displayed.
5) If they answer No, the JComboBox is instructed to display the previous
While we expected this code to be run twice (once for the UNSELECT and then once
for the SELECT of the new item), it seems to be running four times, and this
seems to be directly connected to our attempt to revert to the previous
selection - this seems to be triggering the code again (when we remove this line,
it only runs twice).
The relevant code is as follows:
in method itemStateChanged():
} else if (i == JOptionPane.NO_OPTION) {
As you can see, we try to avoid this problem by removing the ItemListener before
calling setSelectedItem() and then restoring it right after, but this does not
What is also strange is that if it is the setSelectedItem() method that is
triggering the code again, why does it run just four times, why is it not an
infinite loop?
Is there a solution or are we trying to do something that is not compatible with
the default behavior of JComboBox?
Shlomo Shizgal
Nathan Pruett
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use a boolean flag in the listener to test if the user is setting the combobox or the listener is...

  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!