Changing the frame content area after pressing a button

I want to be able to set the content area of ​​a JFrame after clicking a button inside one of these JPanels.

My architecture consists of a controller that creates a JFrame and the first JPanel inside it. Starting with the first JPanel, I call the method: setcontentpane (JPanel jpanel) on the controller. However, instead of loading the transferred JPanel, it does nothing but delete all panels (see code below)

ActionListener inside 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 someone tell me what I am doing wrong? Thanks:)

+7
source share
3 answers

Call revalidate, then redraw. This tells layout managers to make 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 exchange JPanels, you need to use CardLayout and do the dirty work.

+16
source

Whenever you change the frame retention hierarchy, you should call pack() .

From the docs:

Causes this window to have a preferred size and layouts for its Subcomponents. [...] The window will be confirmed after the preferred size is calculated.

+2
source

I found a way to do what I have outlined above.

The implementation of the setpanel method is as follows:

 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 in my code (regarding layout managers and preferred sizes, since package () still compresses the window), but at least the above method works like this :)

+2
source

All Articles