Why is itemStateChanged on JComboBox is called twice when changed?

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

    The code is:

    public class Tester {
    
        private JComboBox box;
    
        public Tester() {
    
            box = new JComboBox();
            box.addItem("One");
            box.addItem("Two");
            box.addItem("Three");
            box.addItem("Four");
    
            box.addItemListener(new ItemListener() {
    
                public void itemStateChanged(ItemEvent e) {
                    if (e.getStateChange() == 1) {
    
                        JOptionPane.showMessageDialog(box, e.getItem());
                        System.out.println(e.getItem());
                    }
                }
            });
    
            JFrame frame = new JFrame();
            frame.getContentPane().add(box);
            frame.pack();
            frame.setVisible(true);
        }
    }
    

提交回复
热议问题