在開發 Eclipse RCP 應用程式時,為了提供良好的使用者體驗,我們通常需要在後台執行耗時操作(如檔案匯入、資料同步、報表產生等),並即時向使用者顯示執行進度。Eclipse 平台提供了 ProgressView 組件,專門用於在工作台中統一展示這些後台任務的進度狀態。本文將詳細記錄如何在 RCP 專案中整合並使用 ProgressView。
ProgressView 是 Eclipse 4.x 架構下的一個獨立外掛,它從原本的 Workbench 服務中解耦出來,專門負責收集並顯示 IProgressService 回報的任務進度。它以視圖的形式呈現,支援多任務並行顯示、取消操作、錯誤報告等功能,是構建專業級 RCP 應用的重要元件之一。
由於 ProgressView 不包含在標準的 Eclipse SDK 套件中,我們需要從官方更新站點手動安裝:
https://hudson.eclipse.org/platform/job/eclipse4-progress-view/lastSuccessfulBuild/artifact/releng/org.eclipse.e4.ui.progress.update/target/repository/ProgressViewDemo),勾選 "Create a simple content" 以生成基礎應用結構。MANIFEST.MF,在 Dependencies 頁籤下的 Required Plug-ins 區域,點擊 Add... 按鈕,搜尋並加入 org.eclipse.e4.ui.progress 外掛。Eclipse 4 使用應用模型定義 UI 結構,我們需要透過 Add-ons 和 Parts 來啟用並顯示 ProgressView。
Application.e4xmi,展開應用模型樹,右鍵點選 Add-ons → New Child → AddOn。bundleclass://org.eclipse.e4.ui.progress/org.eclipse.e4.ui.progress.ProgressViewAddon此 Add-on 會在應用啟動時自動初始化進度服務,確保後續任務能正確回報進度。
progressViewPartbundleclass://org.eclipse.e4.ui.progress/org.eclipse.e4.ui.progress.ProgressViewEclipse 使用 Job API 管理後台任務。以下範例示範如何在按鈕點擊事件中建立一個模擬長時間運算的 Job,並透過 SubMonitor 精細回報進度:
button.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent arg0) {
Job job = Job.create("資料匯入任務", monitor -> {
SubMonitor subMonitor = SubMonitor.convert(monitor);
subMonitor.beginTask("開始匯入資料...", 5000); // 總工作量 5000 單位
for (int i = 0; i < 50; i++) {
try {
Thread.sleep(500L); // 模擬耗時操作
} catch (Exception e) {
e.printStackTrace();
}
subMonitor.worked(100); // 每次推進 100 單位
}
return Status.OK_STATUS;
});
job.schedule(); // 提交給 Job Manager 排程執行
}
@Override
public void widgetDefaultSelected(SelectionEvent arg0) {}
});
IJobFunction 的 Lambda 運算式。beginTask() 設定總工作量,worked() 遞增已完成量。啟動應用後,點擊按鈕觸發任務,ProgressView 視圖將即時顯示:
worked(100) 遞增想深入了解 Eclipse Jobs API 的進階用法(如任務依賴、規則、排程器等),強烈推薦參考 Vogella 教學:
Eclipse Jobs Tutorial
透過引入 org.eclipse.e4.ui.progress 外掛、在應用模型中註冊 ProgressViewAddon 與 ProgressView,並配合標準的 Job + SubMonitor API,我們可以輕鬆為 RCP 應用加入專業級的後台任務進度監控功能。這不僅提升了使用者體驗,也符合 Eclipse 4 架構的模組化設計理念。