resultCombo = new JComboBox();
resultCombo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent ie) {
sampleText=resultCombo.getSelectedItem().toString();
System.out.println("SampleText : "+sampleText);
}
});
output:
SampleText : selectedword
SampleText : selectedword
Why this event is called twice when selecting item in combobox.?
The itemStateChanged() method is invoked automatically whenever you click or unclick on the registered checkbox component. public abstract void itemStateChanged(ItemEvent e);
JComboBox is a part of Java Swing package. JComboBox inherits JComponent class . JComboBox shows a popup menu that shows a list and the user can select a option from that specified list . JComboBox can be editable or read- only depending on the choice of the programmer .
JComoboBox ItemListener does get called twice for a single change. Once for SELECTED event and once for DESELECTED event.
See this tutorial page on how to write an ItemListener.
Basically what you have to do is
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
//Do any operations you need to do when an item is selected.
} else if(e.getStateChange() == ItemEvent.DESELECTED){
//Do any operations you need to do when an item is de-selected.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With