Swing/ProgressComboBox のバックアップソース(No.6)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- バックアップ を表示
- Swing/ProgressComboBox へ行く。
- 1 (2011-09-05 (月) 17:17:06)
- 2 (2012-12-18 (火) 19:25:42)
- 3 (2013-09-20 (金) 04:33:03)
- 4 (2014-12-02 (火) 01:34:54)
- 5 (2015-01-04 (日) 07:14:40)
- 6 (2015-03-19 (木) 16:32:46)
- 7 (2017-02-11 (土) 23:21:30)
- 8 (2017-12-27 (水) 18:27:41)
- 9 (2018-02-24 (土) 19:51:30)
- 10 (2019-12-17 (火) 13:57:50)
- 11 (2021-06-19 (土) 17:18:26)
--- title: JComboBox内にJProgressBarを表示 tags: [JComboBox, ListCellRenderer, JProgressBar, SwingWorker] author: aterai pubdate: 2011-09-05T17:17:06+09:00 description: JComboBox内にJProgressBarを設定して進捗を表示します。 hreflang: href: http://java-swing-tips.blogspot.com/2011/09/jprogressbar-in-jcombobox.html lang: en --- * 概要 [#a84bee81] `JComboBox`内に`JProgressBar`を設定して進捗を表示します。 #download(https://lh6.googleusercontent.com/-wtOABuv6qdQ/TmR3t1oq-qI/AAAAAAAABBg/jbHLwwMR1gc/s800/ProgressComboBox.png) * サンプルコード [#xbdbd6e8] #code(link){{ class ProgressCellRenderer extends DefaultListCellRenderer { 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(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 #comment