• category: swing folder: SortingAnimations title: JComboBoxのモデルとしてenumを使用する tags: [JComboBox, Enum, Animation, SwingWorker] author: aterai pubdate: 2007-07-09T14:59:22+09:00 description: JComboBoxのモデルとしてenumを使用します。 image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTTcZXYeSI/AAAAAAAAAkY/_frjM9wSJsc/s800/SortingAnimations.png

概要

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以上)を使用したキャンセル機能を追加
    • 全画面の書き換えを止めて、移動する点のみウェイトを入れて再描画するように変更

参考リンク

コメント