Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all components in a JPanel dynamically

Tags:

java

swing

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
like image 525
Krishan Avatar asked Nov 29 '22 14:11

Krishan


1 Answers

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

ChildPanel2.removeAll();
ChildPanel2.revalidate();
ChildPanel2.repaint();
like image 178
rdonuk Avatar answered Dec 05 '22 11:12

rdonuk