JComboBoxでアイテムが選択されていない場合のプレースホルダ文字列を設定する
Total: 3564, Today: 3, Yesterday: 0
Posted by aterai at
Last-modified:
Summary
JComboBoxでアイテムが選択されていない場合、代わりに表示するプレースホルダ文字列を設定します。
Screenshot

Advertisement
Source Code Examples
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) {
// ???: 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, KotlinDescription
上記のサンプルでは、編集不可のJComboBoxにアイテムが選択されていない場合にヒントとしてプレースホルダ文字列を表示するリストセルレンダラーを設定しています。
DefaultListCellRenderer#getListCellRendererComponent(...)メソッドをオーバーライドし、引数のvalueがnullである場合のみヒント文字列を表示するよう設定- 引数の
Object valueがnullの場合ではなくリストのindexが-1の場合にヒント文字列を表示すると、マウスクリックでJComboBoxの選択状態が変更不可になる?
- 引数の
- リストセルレンダラー側でプレースホルダ文字列を表示しているため
JComboBoxのモデル側にプレースホルダ文字列を含める必要がない
Reference
- JTextFieldにフォーカスと文字列が無い場合の表示
- JTextFieldに透かし画像を表示する
- JPasswordFieldにヒント文字列を描画する
- ComboBoxEditorにJLayerを設定してプレースホルダ文字列を表示する
- こちらは編集可能な
JComboBoxでプレースホルダ文字列を表示する場合のサンプル
- こちらは編集可能な