matel matel - 3 years ago 91
Java Question

Please help me to understand JPanel

I am having difficulties to understand the core of

and layout

In the following code I would have expected to see both panel but can only see the yellow one and it takes all the size of the frame....

class NewFrame extends JFrame implements ComponentListener {

public NewFrame() {

this.setSize(600, 600);
JPanel panel = new JPanel(new BorderLayout());

JPanel panel2 = new JPanel(new BorderLayout());


Answer Source

You have assigned a layout manager to your panels (which is actually not required here) but not to their parent container. If you place panels in a container without a layout manager they will be placed on top of each other, meaning that you only see the last one that has been placed.

You need to assign the BorderLayout manager to the ContentPane of your JFrame:

Container cp = this.getContentPane();
cp.setLayout(new BorderLayout());

Then add your panels to it:


You still won't see the EAST panel because it doesn't contain any components. In BorderLayout, the CENTER region always fills as much space as possible while the other regions only take the space needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download