Andrew V
Andrew V

Reputation: 522

JButton removing all the others jcomponent from a jpanel

I have this actionlistener added to a button:

//The ActionListener for the home button
ActionListener homeActionListener = new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        removeAll();
        Home home = new Home();
        add(home);
    }
};

This is the code for jpanel and jbutton:

//creating the jpanel which will hold the buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setBounds(0,0,600,100);
buttonPanel.setBackground(Color.GRAY);
add(buttonPanel);

//creating the jbutton to send the user to the home page
JButton home = new JButton("Home");
home.setBounds(25,25,100,50);
buttonPanel.add(home);

How can i make it so it deletes every component of the jframe except for that jpanel called buttonPanel?

Upvotes: 0

Views: 539

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347204

A possible solution would be to create a central panel which holds all the other components and simply use removeAll on this container instead.

Be careful calling removeAll on a JFrame, it will remove the root pane which isn't really what you want.

And what HovercraftFullEels said

Upvotes: 4

Benjamin
Benjamin

Reputation: 2286

getContentPane().removeAll();

removeAll() remove all component on frame.

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

  1. Stop using null layout and setBounds. While using null layout may seem to a newbie the better way to create complex GUI's, it's a fallacy, and more you create Swing GUI's the more you learn to respect and use the layout managers and see that these creatures help immensely in creating flexible, beautiful and if need be, complex GUI's. Then you can let them size them selves appropriately by calling pack() prior to setting them visible.
  2. Swap JPanels using a CardLayout. Tutorial link here.

.... and what MadP has to say!

Upvotes: 4

Related Questions