Why is itemStateChanged on JComboBox is called twice when changed?

后端 未结 10 1870
忘掉有多难
忘掉有多难 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:16

    Have a look at this source:

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Tester {
    
        public Tester(){
    
            JComboBox box = new JComboBox();
            box.addItem("One");
            box.addItem("Two");
            box.addItem("Three");
            box.addItem("Four");
    
            box.addItemListener(new ItemListener(){
                public void itemStateChanged(ItemEvent e){
                    System.out.println(e.getItem() + " " + e.getStateChange() );
                }
            });
    
            JFrame frame = new JFrame();
            frame.getContentPane().add(box);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String [] args) {
            Tester tester = new Tester();
        }
    }
    

    Use the getStateChange to determine if an item is selected or deselected

提交回复
热议问题