aspose file tools*
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 EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JComboBox and ItemListener" Watch "JComboBox and ItemListener" New topic
Author

JComboBox and ItemListener

Shlomo Shizgal
Greenhorn

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
selection.
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) {
experimentTypeCombo.removeItemListener(this);
experimentTypeCombo.setSelectedItem(currentExperimentType);
experimentTypeCombo.addItemListener(this);
}
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
help.
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?
Thanks,
Shlomo Shizgal
Nathan Pruett
Bartender

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...



-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JComboBox and ItemListener
 
Similar Threads
How do I accomplish this?
weird thing happening with JComboBox
Urgent JComboBox!!!
ComboBox ItemListener calling twice..
JComboBox.setSelectedItem() does not update the displayed value