絕對佈局(Absolute Layout / Null Layout)指不使用任何佈局管理器,開發者手動指定每個組件的精確坐標 (x, y) 與尺寸 (width, height)。適用於原型快速驗證、固定尺寸工具窗口、圖形編輯器等場景。
setLayout(null) 禁用佈局管理器setBounds(x, y, width, height) 設置幾何屬性setBounds 確定屏幕位置與大小public class AbsoluteLayoutDemo extends JFrame {
public AbsoluteLayoutDemo() {
setTitle("絕對佈局示例");
setLayout(null); // 關鍵:禁用佈局管理器
setBounds(100, 100, 400, 300); // 窗口位置與大小
Container cp = getContentPane();
JButton btn1 = new JButton("按鈕 1 (10,30)");
btn1.setBounds(10, 30, 120, 30);
JButton btn2 = new JButton("按鈕 2 (150,80)");
btn2.setBounds(150, 80, 120, 30);
JLabel label = new JLabel("標簽 (50,150)");
label.setBounds(50, 150, 200, 25);
label.setOpaque(true);
label.setBackground(Color.YELLOW);
cp.add(btn1);
cp.add(btn2);
cp.add(label);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(AbsoluteLayoutDemo::new);
}
}
(0,0) 位於容器內邊距左上角(不含標題欄、邊框)getInsets() 可獲取容器內邊距| 優點 | 缺點 |
|---|---|
| 像素級精確控制 | 窗口縮放/分辨率變化時佈局崩壞 |
| 代碼直觀、易理解 | 跨平台外觀不一致(字體、DPI 差異) |
| 無佈局管理器開銷 | 維護成本極高:添加/移動組件需手動重算所有坐標 |
| 適合固定尺寸原型 | 國際化(文本長度變化)導致重疊/截斷 |
| 無響應式能力,不適應現代 UI 需求 |
addComp(Container, Component, x, y, w, h) 統一管理getPreferredSize() 而非硬編碼
4. 監聽 ComponentListener 動態調整(極其複雜,不推薦)
5. 考慮 GridBagLayout 或 MigLayout(第三方)獲得類似靈活性但具備響應式能力
將詳細講解 FlowLayout(流式佈局)、BorderLayout(邊界佈局)、GridLayout(網格佈局) 三大核心佈局管理器的特性、構造參數與組合實戰。