使用 GridLayout(3, 3) 設定容器為 3 行 3 列,加入 4 個面板後,實際顯示僅 2 列,且第 4 個面板大小與前三個不同。
GridLayout(rows, cols) 中,當 rows > 0 時,cols 參數會被忽略,實際列數由 rows 與元件總數決定。本例中 rows=3、元件數=4,列數 = ceil(4/3) = 2。GridLayout(2, 1)(兩行一列),導致其高度較大,影響整體佈局。import java.awt.*;
import javax.swing.*;
public class JPanelTest extends JFrame {
public JPanelTest() throws HeadlessException {
Container c = getContentPane();
// 設定 rows=0,cols=3,讓列數固定為 3,行數自動計算
c.setLayout(new GridLayout(0, 3, 10, 10));
JPanel p1 = new JPanel(new GridLayout(1, 1, 10, 10));
JPanel p2 = new JPanel(new GridLayout(1, 2, 10, 10));
JPanel p3 = new JPanel(new GridLayout(1, 2, 10, 10));
// 修正 p4 為單行單列
JPanel p4 = new JPanel(new GridLayout(1, 1, 10, 10));
p1.add(new JButton("1"));
p2.add(new JButton("2"));
p3.add(new JButton("3"));
p4.add(new JButton("4"));
c.add(p1);
c.add(p2);
c.add(p3);
c.add(p4);
setSize(400, 500);
setVisible(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new JPanelTest();
}
}
rows 設為 0,cols 設為期望列數。