• title: JTabbedPaneのタブにJProgressBarを表示 tags: [JTabbedPane, JProgressBar, SwingWorker] author: aterai pubdate: 2008-01-28T12:53:45+09:00

概要

JTabbedPaneのタブにJProgressBarを配置して、進捗を表示します。

サンプルコード

private final Executor executor = Executors.newCachedThreadPool();
public void addTab(String title, final Component content) {
  super.addTab(title, new JLabel("Loading..."));
  final JProgressBar bar = new JProgressBar();
  final int currentIndex = getTabCount()-1;
  final JLabel label = new JLabel(title);
  Dimension dim = label.getPreferredSize();
  int w = Math.max(80, dim.width);
  label.setPreferredSize(new Dimension(w, dim.height));
  Insets tabInsets = UIManager.getInsets("TabbedPane.tabInsets");
  bar.setPreferredSize(new Dimension(w, dim.height-tabInsets.top-1));
  setTabComponentAt(currentIndex, bar);
  SwingWorker worker = new SwingWorker() {
    @Override public Object doInBackground() {
      int current = 0;
      int lengthOfTask = 180;
      while(current<lengthOfTask) {
        if(!bar.isDisplayable()) return "NotDisplayable";
        try {
          Thread.sleep(25);
        }catch(InterruptedException ie) {
          return "Interrupted";
        }
        current++;
        setProgress(100 * current / lengthOfTask);
      }
      return "Done";
    }
    @Override public void done() {
      setTabComponentAt(currentIndex, label);
      setComponentAt(currentIndex, content);
    }
  };
  worker.addPropertyChangeListener(new ProgressListener(bar));
  executor.execute(worker); //JDK 1.6.0_18
  //worker.execute();
}
View in GitHub: Java, Kotlin

解説

JDK 6で追加された以下の機能を使用しています。

  • SwingWorker
  • JTabbedPaneのタブにコンポーネントを配置

参考リンク

コメント