java 如何动态删除JPanel中的所有组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38349445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete all components in a JPanel dynamically
提问by Krishan
Requirement is that i have 2 panels and ie. Panel1 , Panel2. Panel1 will have 2 button, when i click on any button, then Panel should should dynamically show components that are specific to that button on Panel1.
要求是我有 2 个面板,即。面板 1 、面板 2。Panel1 将有 2 个按钮,当我单击任何按钮时,Panel 应动态显示特定于 Panel1 上该按钮的组件。
public class ListenerForRadioButton implements ActionListener{
JButton browseGlobal;
JFrame ParentFrame = new JFrame("Bla-Bla");
JPanel ChildPanel2 = new JPanel();
JButton upload ;
public ListenerForRadioButton(JFrame JFrameConstructor, JPanel JPanelConstructor, JButton uploadConstructor ){
this.ParentFrame = JFrameConstructor;
this.ChildPanel2 = JPanelConstructor;
this.upload = uploadConstructor;
}
public void actionPerformed(ActionEvent event){
//ChildPanel2.remove(upload);
ChildPanel2.remove(upload);
System.out.println("My listener is called");
}//end of method }//end of class
}//方法结束 }//类结束
Public class Create_JFrame extends JFrame{
公共类 Create_JFrame 扩展 JFrame{
public Create_JFrame(){
//Create a Frame
JFrame ParentFrame = new JFrame("Bla-Bla");
JPanel ChildPanel1 = new JPanel();
JPanel ChildPanel2 = new JPanel();
JButton Option1 = new JButton("Option1");
JButton browse = new JButton("Browse");
JButton upload = new JButton("Upload");
//Layout management
ParentFrame.getContentPane().add(BorderLayout.WEST, ChildPanel1);
ParentFrame.getContentPane().add(BorderLayout.EAST, ChildPanel2);
//Create a button
browse.addActionListener(new ListenerForRadioButton(ParentFrame,ChildPanel2,upload)); //Registering my listener
ChildPanel2.add(browse);
ChildPanel2.add(upload);
ChildPanel1.add(Option1);
//Make the frame visible
ParentFrame.setSize(500, 300);
ParentFrame.setVisible(true);
}//end of Main
}//end of Class
回答by rdonuk
With removeAll()
you can remove all components from a Container
.
有了removeAll()
你可以从中删除所有组件Container
。
ChildPanel2.removeAll();
ChildPanel2.revalidate();
ChildPanel2.repaint();
回答by Jordi Castilla
Get the components and delete them
获取组件并删除它们
Component[] components = ChildPanel2.getComponents();
for (Component component : components) {
ChildPanel2.remove(component);
}
ChildPanel2.revalidate();
ChildPanel2.repaint();
NOTE:if you do not want to delete all components, just insert a condition before remove
checking if component is candidate to die.
注意:如果您不想删除所有组件,只需在remove
检查组件是否为死亡的候选之前插入一个条件。