---
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
---
* 概要 [#summary]
`JComboBox`でアイテムが選択されていない場合、代わりに表示するプレースホルダ文字列を設定します。

#download(https://drive.google.com/uc?id=1R3IHJMxqNMm4oHGv9wmZ8FXpeZJn0AvEwA)

* サンプルコード [#sourcecode]
#code(link){{
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;
  }
});
}}

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

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

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

* 参考リンク [#reference]
- [[JTextFieldにフォーカスと文字列が無い場合の表示>Swing/GhostText]]
- [[JTextFieldに透かし画像を表示する>Swing/WatermarkInTextField]]
- [[JPasswordFieldにヒント文字列を描画する>Swing/InputHintPasswordField]]

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