我的理解是,当向 BorderLayout 添加组件时,它们会占据整个隔间的大小。将 panel1 添加到 contentPane 的北部时,似乎是这种情况。但是,当我将 panel2 放在 panel3 的北部,并将 panel3 添加到 contentPane 的中心时,panel2 似乎占用了它可以占用的最少空间。
是什么导致了这些尺寸的差异?
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);
}
}