2

我只是想在 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(""));

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

4

2 回答 2

6

我同意@Chris aGridLayout会更容易:

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(""));
于 2011-12-04T00:19:07.190 回答
4

只需向权重属性添加更多值。这告诉它如何布置网格袋 - 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);

然后为您的项目GridBagConstraints提供gridxgridy为新列/行适当地设置(从 0 开始):

GridBagConstraints gbc = new GridBagConstraints();
...
gbc.gridx = 3;
gbc.gridy = 3;
...
contentPane.add(textFieldName, gbc_textFieldName);
于 2011-12-04T00:16:23.823 回答