Click bt, there is no response, the button has been clicked

50 Views Asked by At
public void Init(){
    JPanel panel=new JPanel();
    JButton bt=new JButton("按钮");
    JCheckBox checkBox1=new JCheckBox("aaaaa");
    JCheckBox checkBox2=new JCheckBox("bbbbb");
    JCheckBox checkBox3=new JCheckBox("ccccc");

    JCheckBox checkBox4=new JCheckBox("ddddd");
    JCheckBox checkBox5=new JCheckBox("eeeee");

    bt.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            panel.removeAll();
            panel.add(checkBox4);
            panel.add(checkBox5);
            panel.repaint();
        }
    });

    panel.add(bt);
    panel.add(checkBox1);
    panel.add(checkBox2);
    panel.add(checkBox3);

    frame.add(panel);
}

When I click bt there is no response, the button has been clicked.

I hope to be able to perform the operations in actionPerformed after clicking bt.

1

There are 1 best solutions below

1
bahman karami On

The reason why your code does not work as expected is because you are missing two important steps after removing all the components from the panel. You need to call panel.revalidate() and panel.repaint() to update the panel's layout and appearance. Otherwise, the changes will not be reflected on the screen. You can fix your code:

public void Init(){
    JPanel panel=new JPanel();
    JButton bt=new JButton("按钮");
    JCheckBox checkBox1=new JCheckBox("aaaaa");
    JCheckBox checkBox2=new JCheckBox("bbbbb");
    JCheckBox checkBox3=new JCheckBox("ccccc");

    bt.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            panel.removeAll(); // remove all components from the panel
            panel.revalidate(); // update the panel's layout
            panel.repaint(); // repaint the panel
        }
    });

    panel.add(bt);
    panel.add(checkBox1);
    panel.add(checkBox2);
    panel.add(checkBox3);

    frame.add(panel);
}