2011-11-26 55 views
2

我試圖將兩個JButton彼此相鄰放置在JFrame的中心,當JFrame重新調整大小時,將不會重新調整按鈕的大小。BorderLayout中心命令不會中心

要做到這一點,我把兩個按鈕放在一個面板FlowLayout,然後放置在一箇中心的面板BorderLayout

但是,以下代碼不會在BorderLayout的中心顯示所選面板。

import java.awt.BorderLayout; 
import java.awt.FlowLayout; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class test extends JFrame { 

    private JPanel panel1 = new JPanel(); 
    private JPanel panel2 = new JPanel(); 
    private JButton button1 = new JButton("one"); 
    private JButton button2 = new JButton("two"); 

    public test() { 
     panel1.setLayout(new FlowLayout()); 
     panel1.add(button1); 
     panel1.add(button2); 

     panel2.setLayout(new BorderLayout()); 
     panel2.add(panel1, BorderLayout.CENTER); 

     this.add(panel2); 
    } 

    public static void main(String[] args) { 
     test frame = new test(); 
     frame.setVisible(true); 
     frame.setSize(400, 400); 
     frame.setLocationRelativeTo(null); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
} 
+0

請學習java的命名約定並堅持到他們 – kleopatra

回答

5

設置GridBagLayoutpanel1

panel1.setLayout(new GridBagLayout()); 

編輯:

@trashgod:我必須弄清楚默認限制是怎麼做的。

由於現場GridBagLayout.defaultConstraints的:

此字段保持包含默認 值的網格包約束實例,因此,如果一個組件不具有網格包約束相關聯 與它,則該組件將被分配一個 defaultConstraints的副本。

在常規實踐中,一個必須取得創建GridBagConstraints對象並設置字段指定每個對象上的約束

引述tutorial

首選的方法設置在一個 部件約束是使用Container.add變型中,傳遞一個 GridBagConstraints對象

+0

+1它的工作原理!現在,我必須弄清楚默認約束是如何實現的。 :-) – trashgod

+1

@trashgod,使用weightx/weighty約束的Swing教程:'除非你爲weightx或weighty指定了至少一個非零值,否則所有組件都聚集在它們容器的中心......' – camickr

3
直觀

,因爲它似乎它的行爲是正確的。

panel1被指定儘可能多的屏幕空間,因爲它是panel2中唯一的組件。 FlowLayout然後從可用空間的頂部開始佈置組件,並且只有在填充了所有可用的水平空間後纔將組件進一步向下放置。因此,您可以在框架的頂部找到兩個按鈕。

你可以嘗試使用Box代替:

public class test extends JFrame { 

    private JComponent box = Box.createHorizontalBox(); 
    private JButton button1 = new JButton("one"); 
    private JButton button2 = new JButton("two"); 

    public test() { 
     box.add(Box.createHorizontalGlue()); 
     box.add(button1); 
     box.add(button2); 
     box.add(Box.createHorizontalGlue()); 
     this.add(box); 
    } 

    ... 
} 

水平盒子自動垂直中心組件,以及兩個膠體成分佔據可用任何額外的水平空間,使按鍵坐在框的中心。

0

JPanel默認使用FlowLayout,而FlowLayout默認使用居中對齊...這對我來說比去GridBagLayout甚至BoxLayout更容易。如果您不希望按鈕在面板太小時「換行」,則可以設置最小尺寸。

package example; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class FlowLO extends JFrame 
{ 
    public static void main(String[] args) 
    { 
     FlowLO flowLO = new FlowLO(); 
     flowLO.go(); 
    } 
    public void go() 
    { 
     JPanel centeredPanel = new JPanel(); 
     centeredPanel.add(new JButton("one")); 
     centeredPanel.add(new JButton("two")); 
     getContentPane().add(centeredPanel); 
     pack(); 
     setVisible(true); 
    } 
}