2012-09-22 29 views
0

我正在設置一些按鈕的佈局。我試圖在中間有兩個按鈕,最後一個按鈕。我有兩個在中間,但最後一個在一邊。我怎樣才能將「後退」按鈕設置在其他按鈕下方。 (我研究過這個)。GridBagLayout中間和底部按鈕

public class Options extends JPanel 
{ 
    private static final long serialVersionUID = 1L; 
    JButton b1 = new JButton("Back"); 
    JButton b4 = new JButton("Textures"); 
    JButton b5 = new JButton("Settings"); 

public Options() 
{ 
    setLayout(new GridBagLayout()); 
    GridBagConstraints c = new GridBagConstraints(); 
    c.anchor = GridBagConstraints.CENTER; 
    c.weighty = 1; 
    c.gridx = 0; 
    c.gridy = 0; 
    c.ipadx = 5; 
    add(b5, c); 
    c.ipadx = 1; 
    c.gridy = 1; 
    add(b4, c); 
    c.weighty = 1; 
    c.gridy = 2; 
    c.anchor = GridBagConstraints.PAGE_END; 
    add(b1, c); 
} 
} 

My layout error

編輯: 我已經更新上面我的代碼。偏移誤差已被固定,但b5在頂部而不是居中(b4居中,b1在底部)。

+1

您是否嘗試過加入'GridBagConstraints'與'layout'對象相關聯,並將'GridBagConstraint'對象的'gridx'屬性設置爲相同的索引? –

+0

佈局的設置約束不會執行任何操作。我設置了gridx = 0和gridy = 1。問題在於佈局位於屏幕的頂部,而b1位於底部。 – Coupon22

+0

如果我們要完全理解你做錯了什麼,請創建併發布[sscce](http://sscce.org)。 –

回答

1

這應該是足夠接近的佈局,我認爲你正試圖獲得:

setLayout(new GridBagLayout()); 
    GridBagConstraints c = new GridBagConstraints(); 

    JPanel layout = new JPanel(new GridLayout(0, 1)); 
    layout.add(new JButton("Settings")); 
    layout.add(new JButton("Textures")); 

    c.anchor = GridBagConstraints.CENTER; 
    c.weighty = 1.0; 
    c.gridy = 0; 
    add(layout, c); 

    c.gridy = 1; 
    c.weighty = 0.1; 
    c.anchor = GridBagConstraints.PAGE_END; 
    add(new JButton("Back"), c); 
+0

我試圖用1佈局來做,但是很好。 2作品。這是我想要的佈局,謝謝。 – Coupon22

1

你可以只設置c.gridx0

GridBagConstraints c = new GridBagConstraints(); 
c.weighty = 1.0; 
c.gridx = 0; 
c.anchor = GridBagConstraints.PAGE_END; 
+0

佈局位於屏幕的頂部,而b1位於底部。 – Coupon22

+0

您正在使用2種不同的佈局來添加布局'JPanel'和'back'按鈕。你可以發佈[sscce](http://sscce.org/)嗎? – Reimeus