我的理解是,当将组件添加到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);
}
}
答案 0 :(得分:6)
你的panel3 JPanel没有布局设置,所以它使用JPanel的默认FlowLayout而不是BorderLayout。