【问题标题】:Changing the Grid Size in a GridBagLayout更改 GridBagLayout 中的网格大小
【发布时间】:2012-01-12 09:54:52
【问题描述】:

我只是想在 java swing 中向 GridBagLayout 添加 3 个居中的垂直按钮。现在我相信默认的网格大小是 3x3。我想知道我是否可以改变它并添加更多的列和行。我只是想在一个窗格中制作 3 个居中的等距按钮。

    pane.setLayout(new GridLayout(10,1));
    // Insert a space before the first button
    for (int i = 1; i < 6; i++ ){
        pane.add(new JLabel(""));
    }
    pane.add(new Button("1"));
    pane.add(new Button("2"));
        pane.add(new Button("3"));
    // Insert a space after the last button
    pane.add(new JLabel(""));

这是最终的解决方案谢谢大家!

【问题讨论】:

  • 为什么必须是 GridBagLayout?一列三行的 GridLayout 听起来非常适合您。
  • +1 表示最近几天取得了很大进展
  • 很高兴你在 SO 上找到了你要找的东西 :)

标签: java swing gridbaglayout


【解决方案1】:

我同意@Chris 的观点,GridLayout 会更容易:

myPanel.setLayout(new GridLayout(5,1));
// Insert a space before the first button
add(new JLabel(""));
add(new Button("1"));
add(new Button("2"));
add(new Button("3"));
// Insert a space after the last button
add(new JLabel(""));

【讨论】:

  • 我需要按钮在第一个按钮上方和最后一个按钮下方的空白处。我尝试了 GridLayout 并无法获得此效果。我需要 (2, 2), (3, 2), (4, 2) 处的按钮
  • @MatthewKemnetz 这可以通过在此处插入空标签来实现。请查看我的编辑。
  • +1 以获得更好的输出最好在 JComponents 之间添加 Gap,例如myPanel.setLayout(new GridLayout(5, 1, 10, 10));
【解决方案2】:

只需向权重属性添加更多值。这告诉它如何布置网格包 - 0 表示仅使用所需的空间,然后根据给定的权重划分其余空间。

GridBagLayout gbl = new GridBagLayout();
...
gbl.columnWeights = new double[] {1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
gbl.rowWeights = new double[] {1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
...
contentPane.setLayout(gbl_contentPane);

然后给你的项目GridBagConstraintsgridxgridy 适当地设置(从0)为新的列/行:

GridBagConstraints gbc = new GridBagConstraints();
...
gbc.gridx = 3;
gbc.gridy = 3;
...
contentPane.add(textFieldName, gbc_textFieldName);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    相关资源
    最近更新 更多