2012-09-20 46 views
0

我必须编辑一个gridbag布局有问题,我有奇怪的结果。
预计:
| A | | B |
| - | | C |
| D | | - |java中的Gridbag布局

结果:
| A | | B |
| 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;

的部件由用户添加和用户确定widthheightgridxgridy的值由添加和放置的其他组件决定。

该网格包布局可以正常工作,如说说
* _ _
| A | B |
| _ | C |
它只是似乎并不喜欢它,当C具有2

+3

你应该张贴一些代码,所以我们看到你正在尝试做的。 – SJuan76

+0

嗯。让我看看我是否可以清理方法稍微更一般。 现在让我试着解释它一些: (高度和宽度代表gridbag约束) 我有几个用户创建表与高度1-10和宽度1-2 – Phox

+0

你可以显示一些屏幕截图和一些代码?现在的问题太抽象了。 –

回答

1

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

GridbagConstraints c = new GridbagConstraints(); 
c.fill = GridbagConstraints.BOTH; 
+0

中发布了网格包约束对不起,我的示例A和C是高度为2的组件 – Phox

+0

在这种情况下,您应该更好地发布一些代码。 –

+0

请看我编辑的答案。 –

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); 
}