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
2010-04-26 04:17:11
You will also need to add revalidate() or validate() to this suggestion.
camickr
2010-04-26 16:05:53
+1
A:
Just add the component to center and revalidate() the parent container
container.add(BorderLayout.CENTER, newPanel);
container.revalidate();
objects
2010-04-26 04:17:53
BTW, container.revalidate() should actually be container.validate().
derekerdmann
2010-04-26 12:55:12
-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
2010-04-26 16:04:21
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
2010-04-26 23:41:11