2014-09-29 85 views
2
import java.awt.GridLayout; 

import javax.swing.JButton; 
import javax.swing.JFrame; 

public class GridLayoutTest { 

    public static void main(String[] args) { 
    JFrame.setDefaultLookAndFeelDecorated(true); 
    JFrame frame = new JFrame("GridLayout Test"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLayout(new GridLayout(3, 2)); 
    frame.add(new JButton("Button 1")); 
    frame.add(new JButton("Button 2")); 
    frame.add(new JButton("Button 3")); 
    frame.add(new JButton("Button 4")); 
    frame.add(new JButton("Button 5")); 
    frame.add(new JButton("Button 6")); 
    frame.add(new JButton("Button 7")); 
    frame.add(new JButton("Button 8")); 
    frame.pack(); 
    frame.setVisible(true); 
    } 
} 

我從這個教程網站代碼:http://www.java2s.com/Tutorial/Java/0240__Swing/HowtoUseGridLayout.htm的JFrame - 設置行和列在GridLayout

該程序在屏幕上顯示8個按鈕。我無法理解按鈕的佈局安排。注意row = 3,column = 2。當運行該程序時,按鈕的配置是行= 3和列= 3 ....

更改的行數實際上根據給定的行數改變了佈局,但改變的列數沒有按不會改變佈局,列數將始終保持爲2.爲什麼?這可能是一個屏幕尺寸問題。

回答

2

這是GridLayout類的記錄的行爲。你有沒有read the docs?

當行數和列數已設置 爲非零值,或者由構造方法或setRows和 setColumns方法,指定的列數爲忽略。 相反,列數從指定行數和 在佈局組件的總數量來確定。所以, 例如,如果指定了三行兩列和9個 組件添加到佈局,它們將被顯示爲三個 行三列。僅當行數設置爲零時,指定列數纔會影響 佈局。

「只有當行數設置爲零時,指定列數纔會影響佈局。」因此,如果你想保持不變的列數,行指定爲0:

frame.setLayout(new GridLayout(0, 2));