• category: swing folder: ComboBoxPlaceholder title: JComboBoxでアイテムが選択されていない場合のプレースホルダ文字列を設定する tags: [JComboBox, ListCellRenderer] author: aterai pubdate: 2017-05-01T14:53:34+09:00 description: JComboBoxでアイテムが選択されていない場合、代わりに表示するプレースホルダ文字列を設定します。 image: https://drive.google.com/uc?id=1R3IHJMxqNMm4oHGv9wmZ8FXpeZJn0AvEwA

概要

JComboBoxでアイテムが選択されていない場合、代わりに表示するプレースホルダ文字列を設定します。

サンプルコード

JComboBox<String> combo1 = new JComboBox<>(
    new String[] {"One", "Two", "Three", "Four"});
combo1.setSelectedIndex(-1);
combo1.setRenderer(new DefaultListCellRenderer() {
  @Override public Component getListCellRendererComponent(
        JList<?> list, Object value, int index,
        boolean isSelected, boolean cellHasFocus) {
    // XXX: String str = index < 0 ? "- Select Item -" : value.toString();
    String str = Objects.toString(value, "- Select Item -");
    super.getListCellRendererComponent(
        list, str, index, isSelected, cellHasFocus);
    return this;
  }
});
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、DefaultListCellRenderer#getListCellRendererComponent(...)メソッドをオーバーライドし、引数の値がnullの場合のみ代わりにプレースホルダ文字列を表示するコンポーネントを返すよう設定しています。

リストセルレンダラーでプレースホルダ文字列を表示しているだけなので、JComboBoxのモデル自体にそれを含める必要がありません。

  • 注:
    • インデックスが-1の場合にプレースホルダ文字列を表示するように設定すると、選択が変更できなくなる?

参考リンク

コメント