2

JavaSwingの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に同意し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(""));
于 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 に答える