Top / Eclipse / プラグイン開発のTIPS集 / プログレスモニタを使う

概要

たとえば検索など、時間のかかる処理をするときはダイアログを出して進捗状況を表示するのが親切です。Eclipseにはこの機能が備わっていて、お手前通りに記述すれば割と簡単に実装可能です。やり方は

  • org.eclipse.jface.operation.IRunnableWithProgress?の実装クラスで、検索などの時間のかかる処理ロジックを記述
  • org.eclipse.jface.dialogs.ProgressMonitorDialog?をインスタンス化
  • ProgressMonitorDialog?#run(true,true,IRunnableWithProgress?のインスタンス)を実行。 とすればダイアログ上で、時間のかかる処理が実行されます。

やってみる

具体的に見ると、以下のような感じです。

IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
Shell shell = window.getShell();
// プログレスバーを使う
ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
SearchWithProgress searchThread = new SearchWithProgress(text);
try {
    dialog.run(true, true, searchThread);
} catch (InvocationTargetException e) {
    logger.error(e);
    // 処理中に何らかの例外が発生したときの処理
} catch (InterruptedException e) {
    // キャンセルされたときの処理
    logger.info("キャンセルされました");
    logger.info(e);
}

ダイアログを作って、ビジネスロジックを作って、ダイアログ上でロジックを実行させる、という順番ですね。runメソッドでThrowされる例外は

InterruptedException?
ユーザがダイアログ上のキャンセルボタンをクリックしたときにThrowされる例外です。
InvocationTargetException?
それ以外の例外が発行されたときにThrowされる例外です。

となっています。

では実際にIRunnableWithProgress? を見てみると、

private class SearchWithProgress 
    implements IRunnableWithProgress {
  public void run(IProgressMonitor monitor)
        throws InvocationTargetException, InterruptedException {
    monitor.beginTask("「" + text + "」でGoogleを検索中...", 10);
    try {
      monitor.subTask("スペルチェック");
      monitor.worked(1);
      
      なんか処理
      monitor.worked(3);
      if (monitor.isCanceled()) {
        throw new InterruptedException("Cancel has been requested.");
      }
      
      monitor.subTask("検索中");
      なんか処理
      monitor.worked(3);
      //検索終了
      
      if (monitor.isCanceled()) {
        throw new InterruptedException("Cancel has been requested.");
      }
    } catch (CoreException e) {
      throw new InvocationTargetException(e);
    }
    monitor.worked(10);
    処理終わり
    monitor.done();
  }
}

てな感じになっています。

monitor.beginTask("「" + text + "」でGoogleを検索中...", 10);
タスク名を記述します。
monitor.subTask("スペルチェック");
サブタスク名を記述します。
monitor.worked(1);
進捗率を記述します。
monitor.done();
処理が全て完了したときに記述します。
if (monitor.isCanceled())
ユーザがキャンセルをクリックしたときに、これがTrueに鳴ります。この場合はユーザがキャンセルを押したときに例外 InterruptedException? をThrowするようにしています。
dialog.png

なんか、アプリぽっくなってきました。

次はあこがれの(?)「バックグラウンドで実行」に挑戦かぁ?


この記事は

選択肢 投票
おもしろかった 12  
そうでもない 0  

Top / Eclipse / プラグイン開発のTIPS集 / プログレスモニタを使う

現在のアクセス:5983


添付ファイル: filedialog.png 1069件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2021-12-14 (火) 11:38:53 (862d)