TITLE:JComboBoxのモデルとしてenumを使用する
#navi(../)
*JComboBoxのモデルとしてenumを使用する [#y688293a]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2007-07-09~
更新日:&lastmod;

#contents

**概要 [#y555e3bb]
JComboBoxのモデルとしてenumを使用します。

#screenshot

**サンプルコード [#i89c933e]
#code{{
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());
}}
-&jnlp;
-&jar;
-&zip;

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

コード中で、どのアイテムが選択されているかなどを調べる場合などは、例えば以下のようにして使用します。
#code{{
worker = new SwingWorker<String, Object>() {
  @Override public String doInBackground() {
    try {
      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;
      }
    }catch(InterruptedException ie) {
      return "Interrupted";
    }
    return "Done";
  }
//......
}}

ソートアニメーション自体は、[[Sorting Algorithm Animations from Programming Pearls>http://www.cs.bell-labs.com/cm/cs/pearls/sortanim.html]]から基本部分はそのままコピーしてSwingに移植しています。
-Swing対応
-SwingWorkerでキャンセル可能に

**参考リンク [#z405b484]
-[[Sorting Algorithm Animations from Programming Pearls>http://www.cs.bell-labs.com/cm/cs/pearls/sortanim.html]]
-[[アクティブレンダリング - Javaでゲーム作りますが何か?>http://javagame.main.jp/index.php?%A5%A2%A5%AF%A5%C6%A5%A3%A5%D6%A5%EC%A5%F3%A5%C0%A5%EA%A5%F3%A5%B0]]

**コメント [#bedcfd09]
#comment