java - GridBagLayout gridwidth 不能按预期工作

标签 java swing gridbaglayout

我在使用 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/

相关文章:

java - java多线程中何时重置CyclicBarrier

循环删除 JButton 时发生 Java ArrayIndexOutOfBoundException

java - 如何在 IntelliJ Java Swing 表单中调整标签、文本字段等的大小?

Java Swing GridBagLayout : Is it possible to create rows with different number of columns?

java - 边框布局对齐

java - 可克隆和 WebDriver ( Selenium )

java - 如何在Android中设置默认模式耳机

java - 没有寻路的 Java 游戏中的移动

java - 可以传递 JFrame 作为参数,然后我得到我创建的字段吗?

java - 为什么我的 UI 在浏览器中运行与在我的计算机 (Java Swing) 上运行时会丢失格式?