JPanel:需要布局帮助

JPanel: layout help needed

我想建立这个布局:

它由一个标签、一个文本字段、2 个按钮和一个可变高度的文本区域(从 1 行到 40 多行)组成。我正在尝试使用 GridBagLayout 但没有成功。按钮在彼此之上,我不知道如何设置每个元素的大小并且它们之间没有 space 。这是到目前为止的代码:

    GridBagLayout gridbag = new GridBagLayout();
    this.setLayout(gridbag);
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 4;
    gridbag.setConstraints(lblGuidelines, c);
    this.add(lblGuidelines);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 4;
    gridbag.setConstraints(txtNumberInput, c);
    this.add(txtNumberInput);

    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 2;
    c.weightx = 0.5;
    gridbag.setConstraints(btnCheck, c);
    this.add(btnCheck);

    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 2;
    c.weightx = 0.5;
    gridbag.setConstraints(btnClear, c);
    this.add(btnClear);

    c.gridx = 0;
    c.gridy = 3;
    c.gridwidth = 4;
    gridbag.setConstraints(textArea, c);
    this.add(textArea);

类似...

基本上,您需要将第二个按钮的 gridx 位置设置为 1 而不是 0。此外,在列不存在的地方指定 gridwidth 是没有意义的,它可能会导致问题,但大多数情况下,这些列的虚拟宽度为 0,因此不会有太大意义

GridBagLayout gridbag = new GridBagLayout();
this.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;

JLabel lblGuidelines = new JLabel("Please neter a telephone number and check if it's valid or not");
JTextField txtNumberInput = new JTextField(12);
JButton btnCheck = new JButton("Check");
JButton btnClear = new JButton("Clear");
JTextArea textArea = new JTextArea(20, 12);

c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
c.insets = new Insets(8, 8, 8, 8);
c.weightx = 1;
this.add(lblGuidelines, c);

c.gridx = 0;
c.gridy = 1;
this.add(txtNumberInput, c);

c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.weightx = 0.5;
this.add(btnCheck, c);

c.gridx = 1;
c.gridy = 2;
this.add(btnClear, c);

c.gridx = 0;
c.gridy = 3;
c.gridwidth = 2;
c.weightx = 1;
this.add(new JScrollPane(textArea), c);