小智 10
有趣的是,我遇到了同样的问题,我很惊讶人们正在提出另一个答案,因为他明确地询问动态创建的组件,而不是已经在可获得的变量名下创建的组件,而不是匿名创建的对象.
答案很简单.使用 getComponents()迭代添加到JPanel的组件数组.例如,使用instanceof查找要删除的组件类型.在我的示例中,我删除了添加到JPanel的任何JCheckBox.
//Get the components in the panel
Component[] componentList = panelName.getComponents();
//Loop through the components
for(Component c : componentList){
//Find the components you want to remove
if(c instanceof JCheckBox){
//Remove it
clientPanel.remove(c);
}
}
//IMPORTANT
panelName.revalidate();
panelName.repaint();
Run Code Online (Sandbox Code Playgroud)
使用该方法Container.remove(Component),您可以从容器中删除任何组件.例如:
JPanel j = new JPanel();
JButton btn1 = new JButton();
JButton btn2 = new JButton();
j.add(btn1);
j.add(btn2);
j.remove(btn1);
Run Code Online (Sandbox Code Playgroud)