JComboBox内にJProgressBarを表示
Total: 5209
, Today: 3
, Yesterday: 1
Posted by aterai at
Last-modified:
概要
JComboBox
内にJProgressBar
を設定して進捗を表示します。
Screenshot
![Swing/ProgressComboBox screenshot](https://ateraimemo.com/swing/progresscombobox/screenshot.png)
Advertisement
サンプルコード
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);
}
}
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、index
が-1
(アイテムリストのインデックスではない)の場合はJProgressBar
を返すリストセルレンダラーをJComboBox
に設定して進捗を表示しています。
- ロードボタンが押されたら以下のような
SwingWorker
でJComboBox
にアイテムを追加
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() throws InterruptedException {
int current = 0;
while (current <= max && !isCancelled()) {
Thread.sleep(50);
// setProgress(100 * current / max);
count = 100 * current / max;
publish("test: "+current);
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();
}
});