Why is itemStateChanged on JComboBox is called twice when changed?

后端 未结 10 1864
忘掉有多难
忘掉有多难 2020-12-03 09:32

I\'m using a JComboBox with an ItemListener on it. When the value is changed, the itemStateChanged event is called twice. The first call, the ItemEvent is showing the origin

10条回答
  •  离开以前
    2020-12-03 10:21

    Have a look here,

    box.addItemListener(new ItemListener(){
        public void itemStateChanged(ItemEvent e){
            if(e.getStateChange()== ItemEvent.SELECTED) {
                //this will trigger once only when actually the state is changed
                JOptionPane.showMessageDialog(null, "Changed");
            }
        }
    });
    

    When you select a new option, it will only once call the JOptionPane, indicating that the code there will be called once only.

提交回复
热议问题