Swing GridBagLayout无法分发(删除)空格

时间:2017-05-15 12:58:07

标签: java swing

即使我读过有关重量的内容,但我无法删除下面给出代码片段的空格:

    JPanel panel = new JPanel();
    scrollPane.setViewportView(panel);
    GridBagLayout gbl_panel = new GridBagLayout();
    GridBagConstraints gc = new GridBagConstraints ();
    gbl_panel.columnWidths = new int[]{0, 0, 0, 0, 0};
    gbl_panel.rowHeights = new int[]{0, 0};
    gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
    gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
    panel.setLayout(gbl_panel);
    for(int i = 0;i<3;i++){
        gc.gridy = i;
        panel.add(new JButton("hi"),gc);
    }

That's what I get

That's what I want

它以相等的空间(顶部,中间,底部)分配这3个按钮 如果组件的总大小大于面板的大小(例如添加10个按钮),则没有问题。但是如果组件的总大小小于面板的大小,则它会分配所有空间。我想逐行设置我的组件(顶部到在组件之间的任何空间的底部 很抱歉给您带来不便,谢谢!

1 个答案:

答案 0 :(得分:1)

您需要GridBagConstraints fill字段

来自JavaDocs

 * This field is used when the component's display area is larger
 * than the component's requested size. It determines whether to
 * resize the component, and if so, how.

fill定义组件是否应调整大小以及如何调整。

weight定义组件应使用的额外空间

更新:

添加任何JComponent,例如所有按钮后JPanelfillJPanel设置weight=1。您的按钮权重为0,因此所有额外空间都会添加到面板中。