2

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?

Bartvbl
  • 2,878
  • 3
  • 28
  • 45

2 Answers2

2

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Where should the layoutmanager be? If I, say, create a new JPanel that acts as the container for all the other JPanels, will that JPanel actually resize when the JFrame resizes? – Bartvbl Oct 28 '11 at 12:33
  • See the [Nested Layout Example](http://stackoverflow.com/questions/5621338/about-swing-and-jtable/5630271#5630271) for ideas on how to combine layouts. – Andrew Thompson Oct 28 '11 at 12:49
2

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

mKorbel
  • 109,525
  • 20
  • 134
  • 319