Change contentpane of Frame after button clicked
I want to be able to set a JFrame's contentpane after a button inside one of that frame's JPanels has been clicked.
My architecture consists of a controller which creates the JFrame and the first JPanel inside of it. From within the first JPanel I'm calling a method: setcontentpane(JPanel jpanel) on the controller. However, instead of loading the passed JPanel it does nothing but removing all Panels (see code below)
ActionListener inside of the first JPanel:
public void actionPerformed(ActionEvent arg0) {
controller.setpanel(new CustomPanel(string1, string2));
}
Controller:
JFrame frame;
public void setpanel(JPanel panel)
{
frame.getContentPane().removeAll();
frame.getContentPane().add(panel);
frame.repaint();
}
public Controlle开发者_如何学Cr(JFrame frame)
{
this.frame=frame;
}
Can anyone tell me what I'm doing wrong? Thanks :)
Call revalidate, then repaint. This tells the layout managers to do their layouts of their components:
JPanel contentPane = (JPanel) frame.getContentPane();
contentPane.removeAll();
contentPane.add(panel);
contentPane.revalidate();
contentPane.repaint();
Better though if you just want to swap JPanels is to use a CardLayout and have it do the dirty work.
I found a way to do what I outlined above.
Implementing the setpanel method like this:
public void setpanel(JPanel panel)
{
frame.setContentPane(panel);
frame.validate();
}
did the trick in my case.
I'm sure that I still need to fix something within my code, since pack() still shrinks the window, but at least the method posted above works.
Whenever you change a frame's containment hierarchy, you have to call pack()
.
From the docs:
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. [...] The Window will be validated after the preferredSize is calculated.
精彩评论