2014-01-05 50 views
0

顯示我有一個JPanel,我想添加JRadioButtons它的JradioButton將方式,這是我試過的代碼:更改上的JPanel

private void populateQuestionnaire(Question question){ 
      buttonGroup = new ButtonGroup(); 
      for(Choix c : question.getListChoix()) { 
       radioButton = new JRadioButton(c.getChoixLibelle()); 
       buttonGroup.add(radioButton); 
       jPanel1.add(radioButton); 

      } 
      jPanel1.revalidate(); 
      jPanel1.repaint(); 
    } 

而且我有JPanel佈局FlowLayout

這是JRadioButtons顯示方式:

enter image description here

我想JRadioButtons添加一個在另一個之下,並在JPanel中爲中心。

+0

請參閱[此答案](http://stackoverflow.com/a/20938621/2587435)。它幾乎是你在找什麼。 –

回答

1

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

} 

這使得,實例化和顯示時,下面的窗口:

Screenshot

現在讓我們來看看這段代碼是如何工作的:

考慮以下代碼:

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的構造函數,讓它知道真的正在佈局什麼。

+0

謝謝你的幫助:) –

3

您可以使用BoxLayout來代替使用FlowLayout,它可以從左到右放置項目,並且可以水平或垂直指定放置項目。

您可以在施工設置LayoutManager爲您JPanel

JPanel jpanel1 = new JPanel(new BoxLayout(parentComponent, BoxLayout.Y_AXIS));