gpt4 book ai didi

java - Swing GridBagLayout 无法分配(删除)空白空间

转载 作者:行者123 更新时间:2023-12-02 13:10:18 26 4
gpt4 key购买 nike

即使我读过一些关于weighty的内容,我也无法删除下面给出的代码片段中的空格:

    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 个按钮),则没有问题。但是如果组件的总大小小于面板的大小,则会分配所有空间。我想逐行设置我的组件(顶部到底部组件之间没有任何空间)给您带来的不便敬请谅解,谢谢!

最佳答案

您需要GridBagConstraints 填充字段

来自 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,例如JPanel位于所有按钮之后,并为JPanelweight=1设置fill。您的按钮的权重为 0,因此所有额外的空间都会添加到面板中。

关于java - Swing GridBagLayout 无法分配(删除)空白空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43980197/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com