且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用GridBagLayout在JPanel中对齐组件中心?

更新时间:2023-12-05 11:06:40

问题在于你的 gridwidth 和你的 fill 属性......

The problem is with your gridwidth and your fill properties...

基本上我改变的是......

Basically all I changed was...

addComponent(titleLabel, 0, 0, GridBagConstraints.REMAINDER, 2, inset); // I tried (0,1,2,2) 
addComponent(comboBox1, 3, 0, 1, 3, inset);
addComponent(comboBox2, 3, 2, 1, 3, inset);
addComponent(textField1, 6, 0, 1, 2, inset);
addComponent(equalLabel, 6, 1, 1, 2, inset);
addComponent(textField2, 6, 2, 1, 2, inset);
layoutConstraints.fill = GridBagConstraints.NONE;
addComponent(resultLabel, 8, 0, GridBagConstraints.REMAINDER, 1, inset);
addComponent(convertButton, 10, 0, GridBagConstraints.REMAINDER, 2, inset);

你可以和其他几个人一起玩。

You could play around with a few of the others.

至于定义面板的实际大小,你可以做的***是覆盖 TimeGui的 getPreferredSize 方法 ...

As for defining the actual size of the panel, the best you can do is to override the getPreferredSize method of the TimeGui...

@Override
public Dimension getPreferredSize() {
    return new Dimension(400, 350);
}

这将向父容器建议你希望的大小布置到。请记住,这是一个可选值,布局管理员完全可以忽略它。

Which will "suggest" to the parent container what size you would like to be laid out to. Just remember, this is an optional value and layout managers are well within there rights to ignore it.