java - GridBagLayout 为什么第三列更大?

标签 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

提前致谢。

最佳答案

您可以通过设置 GridBagConstraints.weightx = 1.0 来实现此目的用于按钮。

另一个需要注意的关键事情是我已将文本字段和按钮添加到 JPanel然后添加JPanelJFrame 的内容 Pane 。我没有直接将文本字段和按钮添加到内容 Pane 。

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

关于java - GridBagLayout 为什么第三列更大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55086638/

相关文章:

java - 如何将包含 JSON 的输入 CSV 数据转换为 Spark 数据集?

java - 仅具有垂直滚动的 JPanel 和 JScrollPane

Java:无法重新绘制 ImageIcon

java - 为什么 GUI 应用程序使用左上角而不是左下角?

java - 创建排行榜?

java - Multicastsocket 在无限循环中不断接收相同的消息

java - 是否可以在一行代码中执行两个不同的 "+="和 "-="操作?

java - Dropwizard - 绑定(bind)不匹配 : not a valid substitute for the bounded parameter

java - 如何使用 JRadioButton 选择鼠标单击似乎不起作用

java - 一个事件有两个监听器?