2021-06-08 (火) 11:23:34
  • category: swing folder: IconComboBox title: JComboBoxにアイコンを表示 tags: [JComboBox, JTextField, Icon, ListCellRenderer, MatteBorder, JLabel] author: aterai pubdate: 2004-12-27T01:32:14+09:00 description: JComboBoxを編集可にしてテキスト入力部分とリスト部分にアイコンを表示します。 image: https://lh5.googleusercontent.com/-4rGEnYRGuys/VQfEDJHomCI/AAAAAAAAN0o/vja8KE3Cm-o/s800/IconComboBox.png

概要

JComboBoxを編集可にしてテキスト入力部分とリスト部分にアイコンを表示します。
http://terai.xrea.jp/swing/iconcombobox/screenshot.png

サンプルコード

#spanend
#spanadd
private static Border makeIconBorder(JComponent c, ImageIcon i) {
#spanend
  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);
#spanadd
}
#spanend
#spanadd
View in GitHub: Java, Kotlin
private static Border makeIconComboBorder(JComponent combo, ImageIcon icon) {
  Border b1 = BorderFactory.createMatteBorder(0,icon.getIconWidth(),0,0,icon);
  Border b2 = BorderFactory.createEmptyBorder(0,5,0,0);
  Border b3 = BorderFactory.createCompoundBorder(b1, b2);
  return BorderFactory.createCompoundBorder(combo.getBorder(), b3);
}

解説

上記のサンプルでは、リスト内の各項目にJLabel#setIcon(...)メソッドでアイコンを追加したListCellRendererJComboBoxに設定しています。
  • setEditable(false)
    • JComboBoxが編集不可の場合、リスト内の各項目だけでなくJComboBoxにもアイコンが表示される
  • setEditable(true)
    • 上:
      • JComboBoxの文字列入力欄にはアイコンが表示されない
    • 中:
      • combo.getEditor().getEditorComponent()で取得したJTextFieldMatteBorderを追加して文字列入力欄にアイコンを表示
    • 下:
      • combo.getEditor().getEditorComponent()で取得したJTextFieldにアイコンを追加したJLabelを追加
      • アイコン(JLabel)が文字列と重ならないようにJTextFieldにはその幅だけ余白をとるように設定

参考リンク

コメント