在 SWT 應用程式開發中,Sash 與 SashForm 是建立可調整分割介面的核心元件。本文透過三個範例,從基本 Sash 拖曳到進階 SashForm 多重分割與最大化功能,完整展示這兩個元件的使用技巧。
Sash 提供簡單的分割捲軸功能,支援水平與垂直兩種方向:
// 垂直分割線
Sash sash = new Sash(shell, SWT.BORDER | SWT.VERTICAL);
sash.setBounds(10, 10, 15, 60);
sash.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
System.out.println("Selected.");
sash.setBounds(e.x, e.y, e.width, e.height); // 即時更新位置
}
});
關鍵點:監聽 SWT.Selection 事件,在 handleEvent 中直接套用事件座標 e.x, e.y, e.width, e.height 實現即時拖曳效果。
SashForm 提供更豐富的分割管理,支援巢狀分割與權重分配:
shell.setLayout(new FillLayout());
// 第一層水平分割
SashForm sashForm = new SashForm(shell, SWT.HORIZONTAL);
Text text1 = new Text(sashForm, SWT.CENTER);
text1.setText("Text in pane #1");
Text text2 = new Text(sashForm, SWT.CENTER);
text2.setText("Text in pane #2");
// 第二層垂直分割(巢狀於第一層)
SashForm sashForm2 = new SashForm(sashForm, SWT.VERTICAL);
Label labelA = new Label(sashForm2, SWT.BORDER | SWT.CENTER);
labelA.setText("Label in pane A");
Label labelB = new Label(sashForm2, SWT.BORDER | SWT.CENTER);
labelB.setText("Label in pane B");
// 設定分割權重 (1:2:3)
sashForm.setWeights(new int[]{1, 2, 3});
ControlListener 監聽面板大小變化
text1.addControlListener(new ControlListener() {
public void controlResized(ControlEvent e) {
System.out.println("Resized");
// 可取得 sashForm.getWeights() 獲取當前比例
}
public void controlMoved(ControlEvent e) {}
});
MouseListener 實現面板最大化切換
labelA.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
if (sashForm2.getMaximizedControl() == labelA)
sashForm2.setMaximizedControl(null); // 還原
else
sashForm2.setMaximizedControl(labelA); // 最大化
}
public void mouseDown(MouseEvent e) {}
public void mouseUp(MouseEvent e) {}
});
| 特性 | Sash | SashForm |
|---|---|---|
| 複雜度 | 低階、手動管理 | 高階、自動佈局 |
| 巢狀分割 | 需自行實作 | 原生支援 |
| 權重分配 | 無 | setWeights() |
| 最大化功能 | 無 | setMaximizedControl() |
| 適用場景 | 簡單單一分割線 | 複雜多面板佈局 |
SashForm 內建 FillLayout 管理子元件,大幅簡化分割介面開發,是建構類似 IDE 面板佈局的首選方案。