• title: JComboBoxのモデルとしてenumを使用する tags: [JComboBox, Enum, Animation, SwingWorker] author: aterai pubdate: 2007-07-09T14:59:22+09:00 description: JComboBoxのモデルとしてenumを使用します。

概要

JComboBoxのモデルとしてenumを使用します。

サンプルコード

private static enum SortAlgorithms {
  Isort    ("Insertion Sort"),
  Selsort  ("Selection Sort"),
  Shellsort("Shell Sort"),
  Hsort    ("Heap Sort"),
  Qsort    ("Quicksort"),
  Qsort2   ("2-way Quicksort");
  private final String description;
  private SortAlgorithms(String description) {
    this.description = description;
  }
  @Override public String toString() {
    return description;
  }
}
private final JComboBox algorithmsChoices = new JComboBox(SortAlgorithms.values());
//JDK 1.7.0
//private final JComboBox<Enum> algorithmsChoices = new JComboBox<Enum>(SortAlgorithms.values());
//private final JComboBox<? extends Enum> algorithmsChoices = new JComboBox<>(SortAlgorithms.values());
//private final JComboBox<SortAlgorithms> algorithmsChoices = new JComboBox<>(SortAlgorithms.values());
View in GitHub: Java, Kotlin

解説

enum型でJComboBoxのモデルを作成しています。上記のコードでは、Enum#toString()メソッドをオーバーライドして、JComboBoxの表示はユーザーに分かりやすい名前になるようにしています。

コード中で、どのアイテムが選択されているかなどを調べる場合などは、例えば以下のようにして使用します。

switch ((SortAlgorithms) algorithmsChoices.getSelectedItem()) {
  case Isort:     isort(number);         break;
  case Selsort:   ssort(number);         break;
  case Shellsort: shellsort(number);     break;
  case Hsort:     heapsort(number);      break;
  case Qsort:     qsort(0, number - 1);  break;
  case Qsort2:    qsort2(0, number - 1); break;
}

ソートアニメーション自体は、Sorting Algorithm Animations from Programming Pearlsから基本部分はそのままコピーして、Swingに移植しています。

  • SwingWorkerでキャンセル可能にしたため、実行するには、JDK 6以上が必要
  • 全部書き換えるのを止めて、移動する点のみウェイトを入れてゆっくり描画するように修正

参考リンク

コメント