matel matel - 1 month ago 9
Java Question

Please help me to understand JPanel

I am having difficulties to understand the core of

JPanel
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);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
//panel.setSize(300,300);
panel.setBackground(Color.pink);

JPanel panel2 = new JPanel(new BorderLayout());
panel2.setBackground(Color.yellow);
panel2.setSize(300,300);
this.add(BorderLayout.EAST,panel);
this.add(BorderLayout.CENTER,panel2);

this.setVisible(true);
}
}

Answer

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:

cp.add(BorderLayout.EAST,panel);
cp.add(BorderLayout.CENTER,panel2);

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.