• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JComboBox内にJProgressBarを表示
#navi(../)
RIGHT:Posted by [[aterai]] at 2011-09-05
RIGHT:Posted by &author(aterai); at 2011-09-05
*JComboBox内にJProgressBarを表示 [#a84bee81]
JComboBox内にJProgressBarを設定して進捗を表示します。

-&jnlp;
-&jar;
-&zip;

//#screenshot
#ref(https://lh6.googleusercontent.com/-wtOABuv6qdQ/TmR3t1oq-qI/AAAAAAAABBg/jbHLwwMR1gc/s800/ProgressComboBox.png)

**サンプルコード [#xbdbd6e8]
#code{{
#code(link){{
class ProgressCellRenderer extends DefaultListCellRenderer {
  private final JProgressBar bar = new JProgressBar();
  private final JProgressBar bar = new JProgressBar() {
    @Override public Dimension getPreferredSize() {
      return ProgressCellRenderer.this.getPreferredSize();
    }
  };
  @Override public Component getListCellRendererComponent(
      JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    if(index<0 && worker!=null && !worker.isDone()) {
      bar.setFont(list.getFont());
      bar.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
      bar.setValue(count);
      return bar;
    }else{
      return super.getListCellRendererComponent(
          list,value,index,isSelected,cellHasFocus);
    }
  }
  @Override public void updateUI() {
    super.updateUI();
    if(bar!=null) SwingUtilities.updateComponentTreeUI(bar);
  }
}
}}

**解説 [#gfcaee95]
上記のサンプルでは、indexが負(アイテムリストではない)の場合、JProgressBarを返すセルレンダラーをJComboBoxに設定して進捗を表示しています。
----
ロードボタンが押されたら、以下のようなSwingWorkerで、JComboBoxにアイテムを追加しています。
#code{{
button = new JButton(new AbstractAction("load") {
  @Override public void actionPerformed(ActionEvent e) {
    button.setEnabled(false);
    combo.setEnabled(false);
    combo.removeAllItems();
    worker = new SwingWorker<String, String>() {
      private int max = 30;
      @Override public String doInBackground() {
        int current = 0;
        while(current<=max && !isCancelled()) {
          try {
            Thread.sleep(50);
            //setProgress(100 * current / max);
            count = 100 * current / max;
            publish("test: "+current);
          }catch(Exception ie) {
            return "Exception";
          }
          current++;
        }
        return "Done";
      }
      @Override protected void process(java.util.List<String> chunks) {
        DefaultComboBoxModel m = (DefaultComboBoxModel)combo.getModel();
        for(String s: chunks) {
          m.addElement(s);
        }
        combo.setSelectedIndex(-1);
        combo.repaint();
      }
      @Override public void done() {
        String text = null;
        if(!isCancelled()) {
          combo.setSelectedIndex(0);
        }
        combo.setEnabled(true);
        button.setEnabled(true);
        count = 0;
      }
    };
    worker.execute();
  }
});
}}

//**参考リンク
**コメント [#aaa6602a]
#comment