gpt4 book ai didi

java - GridBagLayout gridwidth 不能按预期工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:42:09 25 4
gpt4 key购买 nike

我在使用 java swing LayoutManager GridBagLayout 时遇到了这个问题。我想要这样的布局

加速器
BB

但是得到这样的布局

加速器
B

尽管 B 的网格宽度为 2,而 A 的网格宽度为 1,但 A 和 B 占用的列数相同。我认为 A、B 和 C 之间不会有一个非常小的列,因为 C 从第 1 列开始. 如果 C 的网格宽度为 1 而不是 2,则不会出现此问题。我对输出感到困惑。

为什么会这样/我该如何解决?

JFrame test = new JFrame();
test.setSize(800,800);
test.setLayout(new GridBagLayout());
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

GridBagConstraints c;

c = new GridBagConstraints();
c.gridx=0;
c.gridy=0;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
test.add(new JButton("A"), c);

c = new GridBagConstraints();
c.gridx=0;
c.gridy=2;
c.gridwidth=2;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
test.add(new JButton("B"), c);

c = new GridBagConstraints();
c.gridx=1;
c.gridy=0;
c.gridwidth=2;
c.gridheight=2;
c.fill = GridBagConstraints.BOTH;
c.weightx = 2;
c.weighty = 2;
test.add(new JButton("C"), c);

test.setVisible(true);

最佳答案

我知道你的感受......似乎 GridBagLayout 在列没有被 1x1 组件填充时将列的宽度减少到 0。我不知道以下是否是最有效的解决方案,但它有效(通过将两个虚拟 JPanel 添加到“膨胀”第 1 列和第 2 列):

JFrame test = new JFrame();
test.setSize(800,800);
test.setLayout(new GridBagLayout());
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

GridBagConstraints c;

c = new GridBagConstraints();
c.gridx=0;
c.gridy=0;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
test.add(new JButton("A"), c);

c = new GridBagConstraints();
c.gridx=0;
c.gridy=1;
c.gridwidth=2;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
test.add(new JButton("B"), c);

c = new GridBagConstraints();
c.gridx=1;
c.gridy=0;
c.gridwidth=2;
c.gridheight=1;
c.fill = GridBagConstraints.BOTH;
c.weightx = 2;
c.weighty = 2;
test.add(new JButton("C"), c);

c = new GridBagConstraints();
c.gridx=1;
c.gridy=2;
c.gridwidth=1;
c.gridheight=0;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.weighty = 0;
test.add(new JPanel(), c);

c = new GridBagConstraints();
c.gridx=2;
c.gridy=3;
c.gridwidth=1;
c.gridheight=0;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.weighty = 0;
test.add(new JPanel(), c);

test.setVisible(true);

关于java - GridBagLayout gridwidth 不能按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32120258/

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