2014-03-24 78 views
0

好的,所以今天我的編程練習遇到了一些麻煩。邊框和流佈局

的練習文字是這樣的:

(使用的FlowLayout經理)收件符合下列要求的程序:

  • 創建一個框架,並設置其佈局的FlowLayout
  • 創建兩個面板並將它們添加到框架
  • 每個面板包含三個按鈕。該面板採用的FlowLayout

的按鈕應該被命名爲「按鈕1」,「按鈕2」等。 (我完成了原碼)

現在我需要改變我的代碼爲的BorderLayout而移動1個面板向南,其他的中心,我嘗試,但它似乎並沒有正確地走出來。按鈕只在頂部和底部。

原始代碼(的FlowLayout):

import javax.swing.*; 
import java.awt.*; 

public class lab5_1 extends JFrame { 

    public lab5_1() { 
     setLayout(new FlowLayout()); 

     // Create two panels 
     JPanel panel1 = new JPanel(); 
     JPanel panel2 = new JPanel(); 


     // Add three buttons to each panel 
     panel1.add(new JButton(" Button 1 ")); 
     panel1.add(new JButton(" Button 2 ")); 
     panel1.add(new JButton(" Button 3 ")); 
     panel2.add(new JButton(" Button 4 ")); 
     panel2.add(new JButton(" Button 5 ")); 
     panel2.add(new JButton(" Button 6 ")); 


     // Add panels to frame 
     add(panel1); 
     add(panel2); 

    } 

    public static void main(String[] args) { 
     lab5_1 frame = new lab5_1(); 
     frame.setTitle(" Exercise 12_1 "); 
     frame.setSize(600,75); 
     frame.setLocationRelativeTo(null); // center frame 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
    } 
} 

我在BorderLayout的嘗試:

public class lab5_2 extends JFrame { 

    public lab5_2() { 
    setLayout(new BorderLayout()); 

    // Create two panels 
     JPanel panel1 = new JPanel(); 
     JPanel panel2 = new JPanel(); 


     // Add three buttons to each panel 
     panel1.add(new JButton(" Button 1 ")); 
     panel1.add(new JButton(" Button 2 ")); 
     panel1.add(new JButton(" Button 3 ")); 
     panel2.add(new JButton(" Button 4 ")); 
     panel2.add(new JButton(" Button 5 ")); 
     panel2.add(new JButton(" Button 6 ")); 

     //Add Panel to frame 
     add(panel1, BorderLayout.CENTER); 
     add(panel2, BorderLayout.SOUTH); 
    } 


    public static void main(String[] args) { 
     lab5_2 frame = new lab5_2(); 
     frame.setTitle(" Exercise 12_2 "); 
     frame.setSize(200, 200); 
     frame.setLocationRelativeTo(null); // center frame 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
    } 
} 
+1

IMO因爲你沒有使用(=填充)'NORTH',也不是'WEST'或者'EAST'區域,CENTER區域填滿了'SOUTH'後留下的空間(至少我理解了[ Oracle文檔 - BorderLayout](http://docs.oracle.com/javase/7/docs/api/java/awt/BorderLayout.html)等)。如果不是這樣,你會看到空的空間*爲未使用的區域。 – pasty

+0

@pasty所以我的代碼是正確的,但放置是關閉的,因爲其餘沒有填充? – Ryan

+0

同意餡餅。中心部分將擴展以填充所有可用空間。也許可以展示你所期望的和你得到的東西的圖片。 – csmckelvey

回答

1

中心區得到儘可能多的可用空間。其他區域只根據需要擴展以填充所有可用空間。