2011-12-04 63 views
2

我只是想在java swing中將3個居中垂直按鈕添加到GridBagLayout中。現在我相信默認網格大小是3x3。我想知道我是否可以改變它並添加更多的列和行。我只是想在一個窗格中創建3個居中等距的按鈕。更改GridBagLayout中的網格大小

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("")); 

這是最終的解決方案謝謝大家!

+2

爲什麼它必須是GridBagLayout?一列三行的GridLayout聽起來非常適合你。 – Chris

+0

+1在前一天取得重大進展 – mKorbel

+0

很高興你發現你在找什麼:) – GETah

回答

6

我@克里斯一個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("")); 
+0

我需要按鈕是第一個按鈕上方的空白和最後一個按鈕下方的空白處。我嘗試了GridLayout,並沒有得到這個效果。 (2,2),(3,2),(4,2) –

+0

@MatthewKemnetz這可以通過在那裏插入空標籤來實現。請參閱我的編輯。 – GETah

+0

我看到它,它出色地工作 –

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); 

然後給你的項目GridBagConstraintsgridxgridy適當設置(從0開始)爲新列/行:

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