Son*_*icN 5 java swing gridbaglayout
我正在使用 java swing LayoutManager GridBagLayout,遇到了这个问题。我想要这样的布局
ACC
BB
但是得到这样的布局
ACC
B
尽管 B 的网格宽度为 2,其中 A 的网格宽度为 1,但 A 和 B 占用的列数相同。我认为 A、B 和 C 之间不会有一个非常小的列,因为 C 从第 1 列开始。问题如果 C 的 gridwidth 是 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);
Run Code Online (Sandbox Code Playgroud)
我知道你的感受...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);
Run Code Online (Sandbox Code Playgroud)