Swing/IconComboBox のバックアップの現在との差分(No.13)
-
category: swing
folder: IconComboBox
title: JComboBoxにアイコンを表示
tags: [JComboBox, Icon, ListCellRenderer, MatteBorder]
tags: [JComboBox, JTextField, Icon, ListCellRenderer, MatteBorder, JLabel]
author: aterai
pubdate: 2004-12-27T01:32:14+09:00
description: JComboBoxを編集可にしてテキスト入力部分とリスト部分にアイコンを表示します。
image:
概要
概要
JComboBox
を編集可にしてテキスト入力部分とリスト部分にアイコンを表示します。
Screenshot

Advertisement
Screenshot

Advertisement
サンプルコード
サンプルコード
private static Border makeIconBorder(JComponent c, ImageIcon i) {
int iw = i.getIconWidth();
Border b1 = BorderFactory.createMatteBorder(0, iw, 0, 0, i);
Border b2 = BorderFactory.createEmptyBorder(0, 5, 0, 0);
Border b3 = BorderFactory.createCompoundBorder(b1, b2);
return BorderFactory.createCompoundBorder(c.getBorder(), b3);
}
View in GitHub: Java, Kotlin解説
- 一番上
- デフォルトの
ListCellRenderer
を使用するJComboBox
です。
- デフォルトの
- 上から二番目
-
JComboBox
フィールドが編集不可の場合、ListCellRenderer
を実装することでアイコン表示することができます。
-
- 下から二番目
-
JComboBox
フィールドが編集可の場合、ListCellRenderer
を実装しても、Editor
部分はアイコン表示されません。
-
- 一番下
-
JComboBox
フィールドが編集可の場合でも、MatteBorder
を使用することでエディタ部分にもアイコンを表示することができます。
-
解説
上記のサンプルでは、リスト内の各項目にJLabel#setIcon(...)
メソッドでアイコンを追加したListCellRenderer
をJComboBox
に設定しています。
参考リンク
-
setEditable(false)
-
JComboBox
が編集不可の場合、リスト内の各項目だけでなくJComboBox
にもアイコンが表示される
-
-
setEditable(true)
- 上:
-
JComboBox
の文字列入力欄にはアイコンが表示されない
-
- 中:
-
combo.getEditor().getEditorComponent()
で取得したJTextField
にMatteBorder
を追加して文字列入力欄にアイコンを表示
-
- 下:
-
combo.getEditor().getEditorComponent()
で取得したJTextField
にアイコンを追加したJLabel
を追加 - アイコン(
JLabel
)が文字列と重ならないようにJTextField
にはその幅だけ余白をとるように設定
-
- 上: