Eclipse 3.1.x 將 SWT 原生庫打包在 org.eclipse.swt.win32.win32.x86_3.1.x.jar 中,不再像舊版本那樣單獨提供 DLL 文件。直接導入解壓目錄會報錯,需正確配置原生庫路徑。
1. 安裝 Eclipse 3.1.x + SWT Designer 插件
2. 定位 JAR:plugins/org.eclipse.swt.win32.win32.x86_3.1.x.jar
3. 使用 WinRAR/7-Zip 解壓該 JAR
4. 在解壓目錄中找到 swt-win32-XXXX.dll(如 swt-win32-3139.dll)
# Windows 命令行示例
copy swt-win32-3139.dll "%JAVA_HOME%\jre\bin\"
# 或手動複製到:
# C:\Program Files\Java\jre1.x.x\bin\
# C:\Program Files (x86)\Java\jre1.x.x\bin\
原理:JVM 默認在 java.library.path 中包含 JRE bin 目錄,System.loadLibrary() 會自動尋找。
# 刪除解壓產生的文件夾
rmdir /s /q org.eclipse.swt.win32.win32.x86_3.1.x
否則 SWT Designer 會錯誤導入該文件夾而非 JAR。
| 方案 | 可靠性 | 適用場景 |
|---|---|---|
| 複製 DLL 到 JRE/bin | ⭐⭐⭐⭐⭐ 最佳 | 開發機、單用戶環境 |
| 項目根目錄放 DLL | ⭐⭐ 不穩定 | 快速測試 |
| 配置 java.library.path | ⭐⭐⭐ 需啟動參數 | 生產部署、多版本共存 |
| 系統 PATH 環境變量 | ⭐⭐⭐ 影響全局 | 機器級統一配置 |
| 錯誤現象 | 原因 | 解決 |
|---|---|---|
| UnsatisfiedLinkError: no swt-win32 in java.library.path | DLL 未在搜索路徑 | 按步驟 2 複製到 JRE/bin 或配置 -Djava.library.path |
| SWT Designer 導入報錯 | 殘留解壓文件夹 | 按步驟 3 刪除解壓目錄重建項目 |
| 64位 Eclipse 載入 32位 DLL | 架構不匹配 | 下載對應架構 SWT 版本 |
| 多 JDK 環境 DLL 複製錯誤 | 運行時用的非預期 JRE | 確認 java.home 路徑,或使用 -Djava.library.path |
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class SWTTest {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("SWT 驗證");
shell.setSize(300, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}
運行無誤報錯且彈出窗口,即配置成功。
掌握 SWT 原生庫加載機制,能避開 Eclipse RCP 開發中最常見的環境配置坑。