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

SWT Sash 與 SashForm 元件應用詳解:可調整分割介面實作

     編輯:Java 相關知識

SWT 進階佈局元件:Sash 與 SashForm 完整指南

在 SWT 應用程式開發中,Sash 與 SashForm 是建立可調整分割介面的核心元件。本文透過三個範例,從基本 Sash 拖曳到進階 SashForm 多重分割與最大化功能,完整展示這兩個元件的使用技巧。

基本 Sash 元件操作

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 多重分割佈局

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});

互動功能增強

  1. 控制事件監聽:ControlListener 監聽面板大小變化
    text1.addControlListener(new ControlListener() {
        public void controlResized(ControlEvent e) {
            System.out.println("Resized");
            // 可取得 sashForm.getWeights() 獲取當前比例
        }
        public void controlMoved(ControlEvent e) {}
    });
  2. 雙擊最大化/還原: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) {}
    });

核心差異與選擇建議

特性SashSashForm
複雜度低階、手動管理高階、自動佈局
巢狀分割需自行實作原生支援
權重分配無setWeights()
最大化功能無setMaximizedControl()
適用場景簡單單一分割線複雜多面板佈局

SashForm 內建 FillLayout 管理子元件,大幅簡化分割介面開發,是建構類似 IDE 面板佈局的首選方案。

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