0

我必须有问题地编辑网格包布局,结果很奇怪。
预期:
| 一个 | | 乙|
| -- | | C |
| D | | -- |

结果:
| 一个 | | 乙|
| D | | C |

A 和 C 的高度为 2 这就是 gridbag 的工作原理吗?有没有强迫它?

我的程序有两列和 n 行。它支持宽度为 2,但只有在第一列时才生效。如果在第二行,它的作用就像宽度为 1。

gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(7, 7, 7, 7);
gbc.weightx = 0.5;
gbc.anchor = GridBagConstraints.NORTH;

组件由用户添加,用户确定widthand height。和值取决于添加gridxgridy放置的其他组件。

网格袋布局适用于
*_ _
|A|B|
|_|C|
当 C 的高度为 2 时,它似乎不喜欢它

4

2 回答 2

1

现在问题已经澄清:

protected static final Insets entryInsets = new Insets(0, 10, 4, 10);
protected static final Insets spaceInsets = new Insets(10, 10, 4, 10);

protected void createPartControl() {
    panel = new JPanel();
    panel.setLayout(new GridBagLayout());

    int gridy = 0;
    gridy = createTextFields(gridy);
}

protected int createTextFields(int gridy) {
    JLabel a = new JLabel("A");
    a.setHorizontalAlignment(SwingConstants.LEFT);
    addComponent(panel, a, 0, gridy, 1, 2, spaceInsets,
            GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

    JLabel b = new JLabel("B");
    b.setHorizontalAlignment(SwingConstants.LEFT);
    addComponent(panel, b, 1, gridy++, 1, 1, spaceInsets,
            GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

    JLabel c = new JLabel("C");
    c.setHorizontalAlignment(SwingConstants.LEFT);
    addComponent(panel, c, 1, gridy++, 1, 1, entryInsets,
            GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

    JLabel d = new JLabel("D");
    d.setHorizontalAlignment(SwingConstants.LEFT);
    addComponent(panel, d, 0, gridy++, 2, 1, entryInsets,
            GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

    return gridy;
}

protected void addComponent(Container container, Component component,
        int gridx, int gridy, int gridwidth, int gridheight, 
        Insets insets, int anchor, int fill) {
    GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
            gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
    container.add(component, gbc);
}
于 2012-09-20T16:25:44.343 回答
1

确保您正在设置GridbagConstraints.BOTH您正在使用的对象的fill属性。GridbagConstraints否则,您将无法在多行上拥有组件。

GridbagConstraints c = new GridbagConstraints();
c.fill = GridbagConstraints.BOTH;
于 2012-09-20T16:02:29.957 回答