Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change contentpane of Frame after button clicked

Tags:

java

swing

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 Controller(JFrame frame)
{
    this.frame=frame;
}

Can anyone tell me what I'm doing wrong? Thanks :)

like image 374
Julian Avatar asked May 15 '11 20:05

Julian


3 Answers

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.

like image 140
Hovercraft Full Of Eels Avatar answered Nov 15 '22 23:11

Hovercraft Full Of Eels


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.

like image 30
Julian Avatar answered Nov 15 '22 23:11

Julian


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.

like image 39
Anon Avatar answered Nov 15 '22 23:11

Anon