This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes JComboBox and ItemListener Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JComboBox and ItemListener" Watch "JComboBox and ItemListener" New topic

JComboBox and ItemListener

Shlomo Shizgal

Joined: Jun 25, 2002
Posts: 1
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

Joined: Oct 18, 2000
Posts: 4121

Use a boolean flag in the listener to test if the user is setting the combobox or the listener is...

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
It is sorta covered in the JavaRanch Style Guide.
subject: JComboBox and ItemListener
jQuery in Action, 3rd edition