Java 桌面應用長期面臨「界面異質、性能低下、啟動緩慢」三大痛點。SWT (Standard Widget Toolkit) 由 Eclipse 團隊開發,最大化調用操作系統原生圖形 API(通過 JNI),僅在 OS 不提供組件時自行模擬。結果:原生外觀、高性能、跨平台,幾乎無法辨別是 Java 程序。
import org.eclipse.swt.widgets.*;
public class OpenShell {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}
編譯:javac -cp swt.jar OpenShell.java
運行:java -Djava.library.path=/path/to/native/libs -cp swt.jar:. OpenShell
org.eclipse.swt.widgets:Button、Combo、Text、Label、Table、**Shell**、**Composite** 等核心組件。org.eclipse.swt.layout:FillLayout、RowLayout、GridLayout(最強大)、StackLayout 等,配合 LayoutData 使用。org.eclipse.swt.custom:CLabel(圖文混排)、StyledText(富文本)、TableEditor 等增強組件。org.eclipse.swt.events:Listener 接口與 Event 類(MouseListener、KeyListener、DisposeListener 等),採用觀察者模式。org.eclipse.swt.graphics:Image、Font、Color、GC(繪圖上下文)。org.eclipse.swt.ole.win32:Windows 下 OLE/ActiveX 嵌入(可內嵌 IE、Word、Excel)。
private void initShell(Shell shell) {
GridLayout gl = new GridLayout(); shell.setLayout(gl);
Composite panel = new Composite(shell, SWT.NONE);
panel.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH));
GridLayout gpl = new GridLayout(); panel.setLayout(gpl);
Color bkColor = new Color(Display.getCurrent(), 200, 0, 200);
panel.setBackground(bkColor);
Text text = new Text(panel, SWT.MULTI | SWT.WRAP);
text.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH));
Button btn = new Button(panel, SWT.PUSH); btn.setText("Push");
btn.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) { text.setText("Hello SWT"); }
});
shell.addDisposeListener(e -> bkColor.dispose()); // 釋放系統資源
}
dispose()。JVM GC 不可控,不可依賴。dispose() 會遞歸銷毀所有子組件及其資源。非 UI 線程直接訪問組件拋出 SWTException。跨線程更新 UI 必須用 Display 方法:
// 異步執行(立即返回)
display.asyncExec(() -> { new Button(panel, SWT.PUSH).setText("Push"); });
// 同步執行(等待完成)
display.syncExec(() -> { /* 耗時 UI 操作 */ });
如 MFC 之於 SDK。提供:
MessageDialog.openWarning(parent, "Warning", "Msg");(SWT 需 30+ 行)。org.eclipse.jface.text)。開發建議:先找 JFace,再用 SWT。
解決 JRE 依賴與源碼暴露問題,工具如 Excelsior JET、Launch4j 可將類編譯為原生可執行文件。