How to align components center in the JPanel using GridBagLayout?

别说谁变了你拦得住时间么 提交于 2019-11-30 09:37:52

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!