FillLayout 是 SWT 中最簡單的佈局管理器。它將父容器的客戶區域平均劃分給所有子元件,每個子元件擁有相同的寬度與高度。子元件可水平(一列)或垂直(一行)排列,無法針對單一元件指定尺寸或間距,適合「單一元件填滿容器」或「少數元件等分空間」的簡單場景。
| 屬性 | 說明 |
|---|---|
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();
}
}
shell.pack() 會依據佈局計算建議尺寸,但此處隨後呼叫 shell.open() 並未固定視窗大小,使用者可自由調整視窗,按鈕會即時重新佈局填滿空間。Composite 承載複雜子佈局pack 行為)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)); // 內部精細佈局
// ... 加入標籤、文字框、按鈕等
setLayout: 子元件會疊在左上角,尺寸為 0。margin 與 spacing: margin 是容器邊緣留白,spacing 是元件之間間距。RowLayout 並設定 pack = true。FillLayout 雖然功能單一,但理解其「平均分配」特性,配合巢狀佈局策略,能快速構建出結構清晰的 UI 骨架。若需更多彈性,請參考 RowLayout、GridLayout 或 FormLayout。