• category: swing folder: BorderSeparator title: JComboBoxのアイテムをBorderで修飾してグループ分け tags: [JComboBox, Border, ListCellRenderer, MatteBorder] author: aterai pubdate: 2005-09-19T09:10:06+09:00 description: JComboBoxのアイテムをBorderを使用して修飾してグループ分けします。 image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTIMVjWegI/AAAAAAAAASY/yM_W_tfnios/s800/BorderSeparator.png

概要

JComboBoxのアイテムをBorderを使用して修飾してグループ分けします。

サンプルコード

JComboBox combobox = new JComboBox();
JSeparator sep = new JSeparator();
ListCellRenderer lcr = combobox.getRenderer();
combobox.setRenderer(new ListCellRenderer() {
  @Override public Component getListCellRendererComponent(
               JList list, Object value, int index,
               boolean isSelected, boolean cellHasFocus) {
    MyItem item = (MyItem) value;
    JLabel label = (JLabel) lcr.getListCellRendererComponent(
                    list, item, index, isSelected, cellHasFocus);
    if (item.hasSeparator()) {
      label.setBorder(
             BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY));
    } else {
      label.setBorder(BorderFactory.createEmptyBorder());
    }
    return label;
  }
});
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement(new MyItem("aaaa"));
model.addElement(new MyItem("eeeeeeeee", true));
model.addElement(new MyItem("bbb12"));
combobox.setModel(model);
combobox.setEditable(true);
View in GitHub: Java, Kotlin
class MyItem {
  private final String  item;
  private final boolean flag;
  public MyItem(String str) {
    this(str, false);
  }
  public MyItem(String str, boolean flg) {
    item = str;
    flag = flg;
  }
  @Override public String toString() {
    return item;
  }
  public boolean hasSeparator() {
    return flag;
  }
}
// ...

解説

レンダラーの中で、JLabelMatteBorderで修飾し、JSeparatorを使用せずにItemをグループ分けしているように見せかけています。

  • JComboBoxが編集可
    • フィールド表示にはListCellRendererではなくJTextFieldが使用されるため、JComboBoxにJSeparatorを挿入する方法より簡単に区切りを表現可能
  • JComboBoxが編集不可
    • JComboBox Items with Separators - Santhosh Kumar's Weblogのようにフィールド表示(index!=-1の場合)で区切りが表示されないようにする必要がある
      combobox.setRenderer(new ListCellRenderer() {
        @Override public Component getListCellRendererComponent(
                     JList list, Object value, int index,
                     boolean isSelected, boolean cellHasFocus) {
          MyItem item = (MyItem) value;
          JLabel label = (JLabel) lcr.getListCellRendererComponent(
                          list, item, index, isSelected, cellHasFocus);
          if (index != -1 && item.hasSeparator()) {
            label.setBorder(
                   BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY));
          } else {
            label.setBorder(BorderFactory.createEmptyBorder());
          }
          return label;
        }
      });
      

参考リンク

コメント