首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

SWT/JFace 佈局管理器詳解:FillLayout 使用完全指南

     編輯:Java 相關知識

什麼是 FillLayout?

FillLayout 是 SWT 中最簡單的佈局管理器。它將父容器的客戶區域平均劃分給所有子元件,每個子元件擁有相同的寬度與高度。子元件可水平(一列)或垂直(一行)排列,無法針對單一元件指定尺寸或間距,適合「單一元件填滿容器」或「少數元件等分空間」的簡單場景。

FillLayout 風格與屬性

屬性說明
type排列方向:SWT.HORIZONTAL(預設,水平排列)或 SWT.VERTICAL(垂直排列)
marginWidth左右邊距(像素)
marginHeight上下邊距(像素)
spacing元件間距(像素)

完整範例:垂直排列三個按鈕

package swt_jface.demo2;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class FillLayoutSample {
    Display display = new Display();
    Shell shell = new Shell(display);

    public FillLayoutSample() {
        FillLayout fillLayout = new FillLayout(SWT.VERTICAL);
        fillLayout.marginHeight = 5;
        fillLayout.marginWidth = 5;
        fillLayout.spacing = 1;

        shell.setLayout(fillLayout);

        Button button1 = new Button(shell, SWT.PUSH);
        button1.setText("button1");

        Button button2 = new Button(shell, SWT.PUSH);
        button2.setText("button number 2");

        Button button3 = new Button(shell, SWT.PUSH);
        button3.setText("3");

        shell.pack();
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) display.sleep();
        }
        display.dispose();
    }

    public static void main(String[] args) {
        new FillLayoutSample();
    }
}

執行結果說明

  • 三個按鈕垂直堆疊,寬度相同(等於視窗寬度減去左右邊距)。
  • 高度相同(視窗高度減去上下邊距與兩個間距,再除以 3)。
  • shell.pack() 會依據佈局計算建議尺寸,但此處隨後呼叫 shell.open() 並未固定視窗大小,使用者可自由調整視窗,按鈕會即時重新佈局填滿空間。

適用場景與限制

✅ 適合場景

  • 工具列、狀態列等單一元件填滿容器
  • 簡單對話框內僅有一個 Composite 承載複雜子佈局
  • 快速原型開發,不需精細控制元件尺寸

❌ 不適合場景

  • 需要元件維持原始大小(pack 行為)
  • 需要元件依比例分配空間(如 7:3 分欄)
  • 需要複雜對齊、跨行/跨列、邊距差異化

進階技巧:嵌套佈局

FillLayout 常作為外層容器,內部嵌套 GridLayout、RowLayout 或 FormLayout 實現精細控制:

Shell shell = new Shell(display);
shell.setLayout(new FillLayout()); // 外層填滿

Composite main = new Composite(shell, SWT.NONE);
main.setLayout(new GridLayout(2, false)); // 內部精細佈局
// ... 加入標籤、文字框、按鈕等

常見錯誤與除錯

  1. 忘記呼叫 setLayout: 子元件會疊在左上角,尺寸為 0。
  2. 混淆 margin 與 spacing: margin 是容器邊緣留白,spacing 是元件之間間距。
  3. 期望元件保持原始大小: FillLayout 強制拉伸,若需保持原始大小請改用 RowLayout 並設定 pack = true。

總結

FillLayout 雖然功能單一,但理解其「平均分配」特性,配合巢狀佈局策略,能快速構建出結構清晰的 UI 骨架。若需更多彈性,請參考 RowLayout、GridLayout 或 FormLayout。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved