2012-04-21 70 views
2

我的理解是,在向BorderLayout添加組件時,它們會佔用整個大小的隔間。將panel1添加到contentPane的北部時,似乎就是這種情況。但是,當我將panel2放在panel3的北部,並將panel3添加到contentPane的中心時,panel2似乎佔用了最小的空間量。Java - BorderLayout - 組件應占用全寬嗎?

什麼是造成這些尺寸的差異?

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); 
    } 

} 

回答

6

您的panel3 JPanel沒有佈局設置,因此它使用JPanel的默認FlowLayout而不是BorderLayout。

+0

哎呀,忘了設置BorderLayout。謝謝。 – Tim 2012-04-21 12:57:05