4

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.

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{

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
Krishan
  • 61
  • 1
  • 1
  • 4
  • Just about any problem statement that starts with words to the effect 'remove all components' can be better solved using a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Jul 13 '16 at 11:39

2 Answers2

22

With removeAll() you can remove all components from a Container.

ChildPanel2.removeAll();
ChildPanel2.revalidate();
ChildPanel2.repaint();
rdonuk
  • 3,921
  • 21
  • 39
2

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.

SOURCES: 1, 2, 3.

Sumanth Ratna
  • 33
  • 1
  • 2
  • 10
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109