Why is itemStateChanged on JComboBox is called twice when changed?

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

    Quote from Java Tutorial:

    "Only one item at a time can be selected in a combo box, so when the user makes a new selection the previously selected item becomes unselected. Thus two item events are fired each time the user selects a different item from the menu. If the user chooses the same item, no item events are fired."

    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 10:27
    private void dropDown_nameItemStateChanged(java.awt.event.ItemEvent evt) {                                                 
    
    
        if(evt.getStateChange() == ItemEvent.SELECTED)
        {
            String item = (String) evt.getItem();
            System.out.println(item);
        }
    
    }
    

    Good Luck!

    0 讨论(0)
提交回复
热议问题