• 追加された行はこの色です。
  • 削除された行はこの色です。
---
category: swing
folder: ComboBoxPlaceholder
title: JComboBoxでアイテムが選択されていない場合のプレースホルダー文字列を設定する
tags: [JComboBox]
author: aterai
pubdate: 2017-05-01T14:53:34+09:00
description: JComboBoxでアイテムが選択されていない場合、代わりに表示するプレースホルダー文字列を設定します。
image: https://drive.google.com/uc?export=view&id=1R3IHJMxqNMm4oHGv9wmZ8FXpeZJn0AvEwA
---
* 概要 [#summary]
`JComboBox`でアイテムが選択されていない場合、代わりに表示するプレースホルダー文字列を設定します。

#download(https://drive.google.com/uc?export=view&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) {
  @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]
- `JComboBox`のモデルにはプレースホルダー文字列を含めない
- `DefaultListCellRenderer#getListCellRendererComponent(...)`メソッドをオーバーライドし、引数の値が`null`の場合のみ代わりにプレースホルダー文字列を表示するコンポーネントを返す
-- インデックスが`-1`の場合にプレースホルダー文字列を表示するように設定すると、選択が変更できなくなる?
-- `JComboBox`のモデルにはプレースホルダー文字列を含める必要がない

//* 参考リンク [#reference]
* コメント [#comment]
#comment
#comment