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.
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()andpanel.repaint()to update the panel's layout and appearance. Otherwise, the changes will not be reflected on the screen. You can fix your code: