gridbaglayout中的重量不正确

时间:2013-07-03 21:08:01

标签: java gridbaglayout

我想使用GridBagLayout在Java中创建GUI。这就是我最终想要的:

enter image description here

因此,我遵循了我在互联网上找到的一些说明,这是我写的代码:

    Panel panel = new Panel();
    panel.setLayout(new GridBagLayout());
    GridBagConstraints gc = new GridBagConstraints();
    gc.fill = GridBagConstraints.BOTH;
    gc.insets = new Insets(5, 5, 5, 5);
    gc.weightx = 7;
    gc.weighty = 7;
    panel.add(new JLabel("title"), gc, 0, 0, 2, 1);
    panel.add(new JButton("button 1"), gc, 2, 0, 1, 1);
    panel.add(new JButton("button 2"), gc, 3, 0, 1, 1);
    panel.add(new JButton("button 3"), gc, 4, 0, 1, 1);
    panel.add(new JButton("button 4"), gc, 5, 0, 1, 1);
    panel.add(new JButton("button 5"), gc, 6, 0, 1, 1);
    panel.add(new JLabel("subtitle"), gc, 0, 1, 7, 1);   
    panel.add(new JButton("list"), gc, 0, 2, 2, 4);  
    panel.add(new JButton("button"), gc, 0, 6, 1, 1);    
    panel.add(new JButton("button"), gc, 1, 6, 1, 1);
    panel.add(new JButton("table"), gc, 2, 2, 5, 5);

我的功能添加:

public void add(Component component, GridBagConstraints constraints, int x, int y, int width, int height) {
    constraints.gridx = x;
    constraints.gridy = y;
    constraints.gridwidth = width;
    constraints.gridheight = height;
    this.add(component, constraints);
}

但是,最后我有这个:

enter image description here

如您所见,该表根本不占用5个单元格,并且该列表不占用4个单元格。有谁知道它为什么会这样?谢谢。

1 个答案:

答案 0 :(得分:1)

如果添加:

,它应该有用
    constraints.weightx = (double) width / 7.0;
    constraints.weighty = (double) height / 7.0;

添加方法。