我正在尝试制作一个3x2的网格。在网格中,我想要一张图片和一个相应的单选按钮。所以图片应该在(0,0)中,图片在(1,0)中。我不能让重量x和重量系统工作,所有的组件都在一条线上。我现在已经去掉了权重。代码如下所示:
//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的常规约定,但我不明白为什么这个方法不能很好地工作。我希望你能帮我添加权重,让它看起来像是图片在左列,相应的单选按钮在右行。
发布于 2015-01-16 13:25:15
在您的例子中,您可以简单地使用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);https://stackoverflow.com/questions/27976784
复制相似问题