2012-09-22 35 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