开发者

Swapping out the center JPanel in a BorderLayout

I have a JPanel sitting inside the center pos开发者_JS百科ition of a BorderLayout of a JFrame. How can I swap out the current JPanel for a new one?


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); 
}


Use a Card Layout which manages this for you.


I got this to work with no z index issues through trial and error.

lets call x the JPanel which has the BorderLayout
lets call y the Component which is currently occupying BorderLayout.Center
lets call z the JPanel to replace in the center position.

   x.remove(y);
   x.add(z);
   x.repaint();
   x.revalidate();

I found if I tried to remove the existing JPanel through the LayoutManager itself, it doesn't work. Instead if you use the remove method of the JPanel the java doc says it notifies the layouts removeLayoutComponent method and seems to do the trick.


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

container.add(BorderLayout.CENTER, newPanel);
container.revalidate();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜