我正在为某些按钮设置布局。我想在中间有两个按钮,最后一个按钮。我有两个在中间,但最后一个是在旁边。如何将“后退”按钮设置为低于其他按钮。 (我研究了这个)。
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在底部)。
答案 0 :(得分:1)
您可以将c.gridx
设为0
:
GridBagConstraints c = new GridBagConstraints();
c.weighty = 1.0;
c.gridx = 0;
c.anchor = GridBagConstraints.PAGE_END;
答案 1 :(得分: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);