GridBagLayout为什么第三列更大?

时间:2019-03-10 10:18:46

标签: java swing user-interface layout-manager gridbaglayout

我正在尝试使按钮相等宽度,并且它们的宽度应该和它们上方的JTextField一样。 代码:

window.setLayout(new GridBagLayout());
GridBagConstraints gb = new GridBagConstraints();

gb.gridx = 0;
gb.gridy = 0;
gb.gridwidth = 3;
gb.fill = GridBagConstraints.HORIZONTAL;
gb.gridwidth = GridBagConstraints.REMAINDER;
window.add(text,gb); //adds JTextField

gb.gridwidth = 1;
gb.gridy++;
window.add(one,gb); //adds JButton
gb.gridx++;
window.add(two,gb); //adds JButton
gb.gridx++;
window.add(three,gb); //adds JButton

Screenshot

当我使用gb.gridwidth = GridBagConstriants.RELATIVE;时会发生这种情况:

Screenshot

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以通过为按钮设置GridBagConstraints.weightx = 1.0来实现。

要注意的另一项关键操作是,我已将文本字段和按钮添加到JPanel,然后将其JPanel添加到了JFrame的内容窗格中。我尚未将文本字段和按钮直接添加到内容窗格中。

import javax.swing.*;
import java.awt.*;

public class EqualWidthButtons
{
  public static void main(String[] args)
  {
    JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());

    GridBagConstraints gb = new GridBagConstraints();
    gb.gridx = 0;
    gb.gridy = 0;
    gb.gridwidth = 3;
    gb.fill = GridBagConstraints.HORIZONTAL;
    panel.add(new JTextField(20), gb);

    gb.gridwidth = 1;
    gb.gridy++;
    gb.weightx = 1.0; // This is the important line
    panel.add(new JButton("1"), gb);

    gb.gridx++;
    panel.add(new JButton("2"), gb);

    gb.gridx++;
    panel.add(new JButton("3"), gb);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new GridBagLayout());
    frame.getContentPane().add(panel, new GridBagConstraints());
    frame.setBounds(300, 200, 400, 300);
    frame.setVisible(true);
  }
}

输出:

enter image description here