FXMLでComboBoxの選択肢を列挙型するには

提供: tknotebook
移動: 案内検索

メインページ>コンピュータの部屋#JavaFX>JavaFX Tips

ComboBoxの選択肢を 列挙型のすると、ComboBoxのvalueプロパティを直接列挙型の プロパティにバインドできるので便利な場合があります。

ComboBoxの個々の項目を列挙型にするには、FXML で、ComboBoxをこんな具合に宣言すればOKです。

<ComboBox>
  <value>
    <BlurType fx:value="THREE_PASS_BOX"/>
  </value>
  <items>
    <FXCollections fx:factory="observableArrayList">
      <BlurType fx:value="ONE_PASS_BOX" />
      <BlurType fx:value="TWO_PASS_BOX" />
      <BlurType fx:value="THREE_PASS_BOX" />
      <BlurType fx:value="GAUSSIAN" />
    </FXCollections>
  </items>
</ComboBox>

fx:value 属性はノードのクラスの valueOfメソッドで文字列からインスタンスの作成することを指示します。

実行時、ComboBoxに表示される各項目の文字列は、列挙名そのままになります。

ちょっとした試験プログラムならこれで充分ですが、列挙名がComboBoxで表示するのにふさわしくない名前ならば、対策は2つあります。

  1. 列挙型が変更可能なら、列挙型の個々の要素の toString() メソッドを override する。
  2. ComboBox の セルファクトリークラスとリストセルクラスを書く。

後者は定型的なので一度覚えれば簡単ですが、結構な行数の実装になります。 こんな感じになります。


リストセルクラス

public  class BlurTypeCell extends ListCell<BlurType> {
  @Override
  protected void updateItem(BlurType item, boolean empty) {
    super.updateItem(item, empty);
    if (empty) {
      setText("なし");
      setGraphic(null);
    } else {
      setGraphic(null);
      if (item == BlurType.ONE_PASS_BOX) {
        setText("ワンパス");
      } else if (item == BlurType.TWO_PASS_BOX) {
        setText("ツーパス");
      } else if (item == BlurType.THREE_PASS_BOX) {
        setText("スリーパス");
      } else if (item == BlurType.GAUSSIAN) {
        setText("ガウシアン");
      }
    }
  }
}

リストセルクラスは、項目の値に応じて、ComboBoxの 項目値をどのようにテキストとグラフィックで表示するかを 決めます。

セルファクトリークラス

public class BlurTypeCellFactory implements 
      Callback<ListView<BlurType>, ListCell<BlurType>> {

  @Override
  public ListCell<BlurType> call(ListView<BlurType> param) {
    return new BlurTypeCell();
 
}

セルファクトリークラスはドロップダウンリストの個々のセルに対応するリストセルを生成するためのクラスです。

ComboBox の FXML

<ComboBox>
  <value>
    <BlurType fx:value="THREE_PASS_BOX"/>
  </value>
  <cellFactory>
    <BlurTypeCellFactory/>
  </cellFactory>
  <buttonCell>
    <BlurTypeCell/>
  </buttonCell>
  <items>
    <FXCollections fx:factory="observableArrayList">
      <BlurType fx:value="ONE_PASS_BOX" />
      <BlurType fx:value="TWO_PASS_BOX" />
      <BlurType fx:value="THREE_PASS_BOX" />
      <BlurType fx:value="GAUSSIAN" />
    </FXCollections>
  </items>
</ComboBox>

FXMLでは cellFactory プロパティだけではなく、buttonCell プロパティもセットしている ことに注意してください。

buttonCell プロパティをセットしないと、ドロップダウンリストの表示は変わりますが、最上位の選択されたリスト要素の表示は変わりません。


表示例 列挙型をコンボボックスに表示.png