It was my understanding that when adding components to a BorderLayout they would take up the full size of the compartment. This seems to be the case below when adding panel1 to the north of the contentPane. However, when I then put panel2 in the north of panel3, and add panel3 to the centre of the contentPane, panel2 seems to take up the most minimal amount of space it can.
What is causing the difference in these sizes?
public class BorderLayoutTesting {
public static void main (String[] args) {
JFrame frame = new JFrame();
JPanel panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
panel1.add(new JLabel("name:"), BorderLayout.WEST);
panel1.add(new JTextField(), BorderLayout.CENTER);
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createLineBorder(Color.black));
panel2.setLayout(new BorderLayout());
panel2.add(new JLabel("your full address with postcode:"), BorderLayout.WEST);
panel2.add(new JTextField(), BorderLayout.CENTER);
Container container = frame.getContentPane();
container.setLayout(new BorderLayout());
container.add(panel1, BorderLayout.NORTH);
JPanel panel3 = new JPanel();
panel3.add(panel2, BorderLayout.NORTH);
container.add(panel3, BorderLayout.CENTER);
panel3.setBorder(BorderFactory.createLineBorder(Color.black));
frame.setSize(500,500);
frame.setVisible(true);
}
}
Your panel3 JPanel has no layout set, and so it uses JPanel's default FlowLayout not BorderLayout.