Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JComboBox itemStateChanged event called twice at a time

Tags:

java

swing

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

like image 998
Sathesh Avatar asked Feb 21 '14 05:02

Sathesh


People also ask

What is itemStateChanged?

The itemStateChanged() method is invoked automatically whenever you click or unclick on the registered checkbox component. public abstract void itemStateChanged(ItemEvent e);

What is a JComboBox?

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 .


1 Answers

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.
    }
}
like image 85
Can't Tell Avatar answered Sep 19 '22 10:09

Can't Tell