BoxLayout
是偉大的,在彼此的頂部堆疊的元素。考慮以下代碼:
public class MyFrame extends JFrame {
public MyFrame() {
ButtonGroup bg = new ButtonGroup();
JRadioButton b1 = new JRadioButton("My Button 1");
JRadioButton b2 = new JRadioButton("My Button 2");
bg.add(b1);
bg.add(b2);
BoxLayout bl = new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS);
this.setLayout(bl);
b1.setAlignmentX(CENTER_ALIGNMENT);
b2.setAlignmentX(CENTER_ALIGNMENT);
this.add(b1);
this.add(b2);
}
}
這使得,實例化和顯示時,下面的窗口:
現在讓我們來看看這段代碼是如何工作的:
考慮以下代碼:
ButtonGroup bg = new ButtonGroup();
JRadioButton b1 = new JRadioButton("My Button 1");
JRadioButton b2 = new JRadioButton("My Button 2");
bg.add(b1);
bg.add(b2);
此代碼做同樣的事情你以前做過,只是爲了例子而簡單一點。它創建一個按鈕組和兩個JRadioButton
s,然後將按鈕添加到按鈕組。現在,當它變得有趣時。
接着,考慮下面的代碼:
BoxLayout bl = new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS);
this.setLayout(bl);
第一行創建一個新的具有BoxLayout
以下參數:
1它被鋪設的容器。 (需要它,因爲它不能被共享。)
2應該佈置組件的軸。 (你想爲你的情況Y軸。)
第二行集合的JFrame的contentPane的佈局,你剛剛創建BoxLayout
。
最後,考慮下面的代碼:
b1.setAlignmentX(CENTER_ALIGNMENT);
b2.setAlignmentX(CENTER_ALIGNMENT);
this.add(b1);
this.add(b2);
這將設置兩個單選按鈕的取向,使得它們的中心將互相對齊和框架的中心。然後將它們添加到框架的內容窗格中。
希望這有助於!
注:我用this.getContentPane()
而構建BoxLayout
,而不是僅僅使用this
的原因是因爲JFrames工作時像add()
和setLayout()
重定向到該框架的內容窗格命令。因此,如果我們在構造函數中使用this
,那麼當我們調用this.setLayout(bl)
時,我們確實會調用this.getContentPane().setLayout(bl)
。但是,我們只是告訴BoxLayout
它將佈置框架,而不是它的內容窗格,因此您會收到一個異常,指出BoxLayout
不能共享。爲了糾正錯誤,我們只需要認識到,我們實際上是通過框架的方法處理內容窗格,並相應地更新BoxLayout的構造函數,讓它知道真的正在佈局什麼。
請參閱[此答案](http://stackoverflow.com/a/20938621/2587435)。它幾乎是你在找什麼。 –