gpt4 book ai didi

java - GridBagLayout 顶部和底部调整间隙

转载 作者:行者123 更新时间:2023-11-30 07:09:51 26 4
gpt4 key购买 nike

我有以下代码:

public Frame() {
super();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.weightx = 1;
c.weighty = 1;
for (int i = 0; i < 10; i++) {
c.gridy = i;
panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.RED, 1));
add(panel, c);
}
}

产生以下框架:
following

由于调整大小(预期),您可以看到顶部和底部元素(用箭头标记)上方和下方有一些空间。

知道如何摆脱两个空白空间或至少摆脱顶部的空白空间吗?
谢谢

ps:我知道这个问题和我之前的一个问题很相似,但是不一样!

最佳答案

问题与如何GridBagLayout有关通过 GridBagConstraints.weighty 管理额外的垂直空间属性(参见 API)。我只引用这一行:

If all the weights are zero, all the extra space appears between the grids of the cell and the top and bottom edges.

当所有权重都为 1(您的情况)时,也会发生同样的情况。事实上,除非由于布局管理器计算可用空间的方式而将第一行或最后一行(或两者)显式设置为填充整个额外空间,否则会发生这种情况。据推测,由于可用空间和行数之间的剩余划分,总是有额外的空间未分配,并且该空间分布在顶部(和/或)底部边缘。

如果你用下一行替换你的循环,那么整个额外的空间将分布在顶部和底部的行中,没有任何间隙,(但中间的行不会占用任何额外的空间):

    //c.weighty = 1; comment this line

for (int i = 0; i < 10; i++) {
c.gridy = i;
c.weighty = (i == 0 || i == 9) ? 1 : 0; // add this line here
panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.RED, 1));
frame.getContentPane().add(panel, c);
}

你可以玩一下这个添加的行,你就会明白我的意思了。

注意:如果您想要分布良好的网格,那么 GridLayout可能是更好的选择。

题外话

  • 当您将组件添加到已显示的容器中时,您需要调用 revalidate()方法。
  • 你应该总是调用pack() before 方法使您的顶级容器可见。

关于java - GridBagLayout 顶部和底部调整间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22632287/

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