[英]JFrame - Setting the Row and Column in a GridLayout
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
該程序在屏幕上顯示 8 個按鈕。 我無法理解按鈕的布局安排。 注意 row=3,column=2。 當我運行程序時,按鈕的排列是row=3和column=3....
改變行數實際上會根據給定的行數改變布局,但改變列數並不會改變布局,列數將始終保持為 2。這是為什么呢? 可能是屏幕尺寸問題。
這是GridLayout
類的記錄行為。 你讀過文檔嗎?
當行數和列數都被構造函數或 setRows 和 setColumns 方法設置為非零值時,指定的列數將被忽略。 相反,列數由指定的行數和布局中的組件總數確定。 因此,例如,如果指定了三行兩列,並且在布局中添加了九個組件,它們將顯示為三行三列。 僅當行數設置為零時,指定列數才會影響布局。
“僅當行數設置為零時,指定列數才會影響布局。” 因此,如果要保持列數不變,請為行指定 0:
frame.setLayout(new GridLayout(0, 2));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.