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

SWT/JFace 入門實戰:從環境搭建到記事本雙版本開發

     編輯:Java 相關知識

SWT/JFace 簡介

特性SWTJFace
來源Eclipse 子項目(IBM 主導)基於 SWT 的高層封裝
底層C 調用原生 GUI API委託 SWT
外觀原生系統風格同 SWT
編程模型較底層、面向過程面向對象、MVC 風格
發布依賴.dll/.so + swt.jar+ 5 個 JFace JAR 包

環境搭建

Windows 下 SWT 必備文件

  • swt-awt-win32-3305.dll
  • swt-gdip-win32-3305.dll
  • swt-wgl-win32-3305.dll
  • swt-win32-3305.dll
  • swt.jar

DLL 放入 PATH 或 -Djava.library.path,JAR 放入 CLASSPATH。

JFace 額外 5 個 JAR(從 Eclipse plugins 目錄獲取)

org.eclipse.core.runtime_3.1.2.jar
org.eclipse.jface_3.1.1.jar
org.eclipse.jface.text_3.1.2.jar
org.eclipse.osgi_3.1.2.jar
org.eclipse.text_3.1.1.jar

記事本程序:SWT 版

核心類

  • Display:系統層橋梁,管理事件循環、資源
  • Shell:用戶層窗口,承載控件
  • Button、Text、FileDialog、MessageBox

關鍵代碼片段

// 主循環
Display display = new Display();
Shell shell = new Shell(display, SWT.DIALOG_TRIM);
shell.setText("第一個 SWT 程序");
shell.setSize(400, 300);

// 控件創建
Button newButton = new Button(shell, SWT.PUSH);
newButton.setLocation(2, 5); newButton.setSize(50, 20); newButton.setText("新建");
// ... openButton, saveButton 同理

Text text = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.WRAP);
text.setLocation(2, 30);
text.setSize(shell.getClientArea().width - 4, shell.getClientArea().height - 35);

// 事件監聽(SelectionAdapter 匿名內部類)
newButton.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent e) {
        fn = ""; shell.setText("第一個 SWT 程序"); text.setText("");
    }
});

// 事件循環
shell.open();
while (!shell.isDisposed()) {
    if (!display.readAndDispatch()) display.sleep();
}
display.dispose();

圖 1:SWT 記事本界面

記事本程序:JFace 版

核心差異

  • 主窗口類繼承 ApplicationWindow
  • 控件創建在 createContents(Composite parent) 回調中
  • Shell 由父類管理,用 parent 替代
public class FirstJFace extends ApplicationWindow {
    public FirstJFace() { super(null); }

    protected Control createContents(Composite parent) {
        // 同 SWT 代碼,將 shell → parent
        Button newButton = new Button(parent, SWT.PUSH);
        // ...
        return parent;
    }

    public static void main(String[] args) {
        FirstJFace aw = new FirstJFace();
        aw.setBlockOnOpen(true);
        aw.open();
        Display.getCurrent().dispose();
    }
}

圖 2:JFace 記事本界面(外觀一致)

選型建議

  • 追求原生性能、精細控制、輕量依賴 → **SWT**
  • 偏好面向對象、MVC 分層、現成視圖幫助類(TableViewer、TreeViewer 等) → **JFace**
  • Eclipse RCP 開發必用 JFace
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved