我试图制作3x2网格。在网格中我想要一张图片和一个相应的单选按钮。因此图片将在(0,0)和图片在(1,0)中。 我无法使用weightx和weighty系统工作,所有组件都停留在一条线上。我现在已经移除了重量。代码如下所示:
//the two numbers are corresponding with coordinates. For field00, x=0 and y=0
GridBagConstraints field00 = new GridBagConstraints();
field00.fill = GridBagConstraints.HORIZONTAL;
field00.gridx = 0;
field00.gridy = 0;
this.add(nokiaPic, field00);
GridBagConstraints field10 = new GridBagConstraints();
field10.fill = GridBagConstraints.HORIZONTAL;
field10.gridx = 1;
field10.gridy = 0;
this.add(nokiaButton, field10);
GridBagConstraints field01 = new GridBagConstraints();
field01.fill = GridBagConstraints.HORIZONTAL;
field01.gridx = 0;
this.add(princessPic, field01);
GridBagConstraints field11 = new GridBagConstraints();
field11.gridx = 1;
field11.gridy = 1;
this.add(princessButton, field11);
To give you an idea:
+--------+--------+
| | |
| pic | Button |
| | |
+--------+--------+
| | |
| pic | Button |
| | |
+--------+--------+
| | |
| pic | Button |
| | |
+--------+--------+
我知道我没有使用GridBagConstraints的常规约定,但我不明白为什么这个方法不能正常工作。我希望你可以帮我增加重量,让它看起来像左边的图片,右边有相应的单选按钮。
答案 0 :(得分:1)
在您的情况下,您可以简单地使用GridLayout
,但如果您仍想使用GridBagLayout
,请使用单GridBagConstraints
:
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(nokiaPic, gbc);
gbc.gridx = 1;
this.add(nokiaButton, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
this.add(princessPic, gbc);
gbc.gridx = 1;
this.add(princessButton, gbc);