Java Swing Combobox removeAllItems calling ItemStateChanged also?

后端 未结 5 1697
无人及你
无人及你 2021-01-15 06:24

My code is quite simple actually. I saw a simple and similar code was from this article.

At first, I have 1 combobox. I have a listener on it called

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 07:00

    The method removeAllItems does not call ItemStateChanged, but it call actionPerformed, you can check it by running this simple code:

    public class Tuto {
    
        public static void main(String[] args) {
            //create the main frame
            JFrame frame = new JFrame();
            frame.setResizable(false);
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setLayout(null);
            frame.setLocation(new Point(10, 10));
            frame.setPreferredSize(new Dimension(400, 300));
    
            JComboBox combo = new JComboBox();
            combo.addItem("item 1");
            combo.addItem("item 2");
            combo.addItem("item 3");
            combo.setBounds(50, 30, 300, 20);
            combo.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    System.out.println(" action Performed ");
                }
            });
            frame.add(combo);
    
            JButton button = new JButton("Remove");
            button.setBounds(50, 100, 100, 30);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    combo.removeAllItems();
                }
            });
            frame.add(button);
    
            frame.pack();
            frame.setVisible(true);
        }
    
    }
    

提交回复
热议问题