views:

69

answers:

3

I have a JPanel sitting inside the center position of a BorderLayout of a JFrame. How can I swap out the current JPanel for a new one?

+1  A: 

Did you try something on the lines of:

void swapCenterPanel(JFrame frame, JPanel oldPanel, JPanel newPanel) {
    frame.getContentPane().remove(oldPanel);
    frame.getContentPane().add(newPanel, BorderLayout.CENTER); 
}
binil
You will also need to add revalidate() or validate() to this suggestion.
camickr
+1  A: 

Just add the component to center and revalidate() the parent container

container.add(BorderLayout.CENTER, newPanel);
container.revalidate();
objects
Works perfectly. Thanks!
derekerdmann
BTW, container.revalidate() should actually be container.validate().
derekerdmann
-1, this solution does not work. It appears to work, but try resizing the frame and the previous panel will now be painted on top of the new panel. This is because of how "Z-Ordering" works in Swing. The proper solution is one of the other two suggestions given, depending on your exact requirement.
camickr
suggest you try it out :) A BorderLayout can only have one component in its center and replaces anything that is already there when you add something.
objects
A: 

Use a Card Layout which manages this for you.

camickr