0

我正在为一些按钮设置布局。我试图在中间有 2 个按钮,最后有一个。我有两个在中间,但最后一个在一边。如何将“后退”按钮设置在其他按钮下方。(我研究过这个)。

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

我的布局错误

编辑:我已经更新了上面的代码。偏移误差已修复,但 b5 位于顶部而不是居中(b4 居中,b1 位于底部)。

4

2 回答 2

2

这应该足够接近我认为您试图获得的布局:

    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);
于 2012-09-22T19:19:34.750 回答
1

你可以设置c.gridx0

GridBagConstraints c = new GridBagConstraints();
c.weighty = 1.0;
c.gridx = 0;
c.anchor = GridBagConstraints.PAGE_END;
于 2012-09-22T16:27:22.570 回答