Bartvbl
Bartvbl

Reputation: 2928

Why does only the last JPanel I add to a JFrame resize?

So I am working on a GUI application using the swing framework. In short, I have 3 JPanels that act as different views of my application. Now the problem is that no matter the order I add the JPanels to my JFrame, only the final JPanel I add resizes when I switch to that view.

Some relevant bits of code:

When creating the window, I first create each individual JPanel, and add it to the JFrame:

 JPanel newPanel = new SomeClassExtendingJPanel();
 this.jframe.add(newPanel);

Next, whenever I switch between views of the application, I hide the panel that is currently active:

 jframe.validate();
 jframe.repaint();
 oldPanel.setVisible(false);

And then activate the to be shown panel:

 jframe.validate();
 jframe.repaint();
 newPanel.setVisible(true);

Does anyone know what could be wrong?

Upvotes: 2

Views: 237

Answers (2)

mKorbel
mKorbel

Reputation: 109823

JFrame's ContentPane has implemented BorderLayout by Default, and there is possible to put only one JComponents to the one Area,

you have to change used LayoutManager or put another JPanels to the other Areas

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

To resize the JFrame with each swap, you could call pack() on it, but this is kludgy having a GUI resize all the time. A better solution is to use the mechanism that Swing has for swapping views -- a CardLayout. This will size the container to the largest dimension necessary to adequately display all of the "card" components.

Check out the CardLayout tutorial and the CardLayout API for more on this.

Upvotes: 2

Related Questions