我正在尝试制作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的常规约定,但我不明白为什么这种方法不能同样有效。希望您能帮助我增加权重,以使其看起来像图片在左列中,而相应的单选按钮在右行中。

最佳答案

在您的情况下,您可能只使用了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);

关于java - 无法使带有重量的GridBagLayout位置起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27976784/

10-11 22:15