首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java Swing GridLayout 顯示列數與面板大小不符的原因與修正

     編輯:程式設計綜合問答

問題現象

使用 GridLayout(3, 3) 設定容器為 3 行 3 列,加入 4 個面板後,實際顯示僅 2 列,且第 4 個面板大小與前三個不同。

原因分析

  • 列數計算規則:GridLayout(rows, cols) 中,當 rows > 0 時,cols 參數會被忽略,實際列數由 rows 與元件總數決定。本例中 rows=3、元件數=4,列數 = ceil(4/3) = 2。
  • 面板大小差異:第 4 個面板內部使用 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();
    }
}

關鍵點總結

  1. 若需固定列數,請將 rows 設為 0,cols 設為期望列數。
  2. 子面板的佈局管理器會影響其內部元件大小,進而影響外層 GridLayout 的單元格尺寸。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved