TITLE:JComboBoxのアイテムをBorderで修飾してグループ分け

JComboBoxのアイテムをBorderで修飾してグループ分け

編集者:Terai Atsuhiro
作成日:2005-09-20
更新日:2022-05-31 (火) 17:36:21

概要

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

プログラム板 Java低速GUI Swing 3の229さんのアイデアを参考にしています。

#screenshot

サンプルコード

public class MainPanel extends JPanel{
  private final JComboBox combobox = new JComboBox();
  public MainPanel() {
    final JSeparator sep = new JSeparator();
    final ListCellRenderer lcr = combobox.getRenderer();
    combobox.setRenderer(new ListCellRenderer() {
    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);
    
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    add(new JTextField());
    add(Box.createVerticalStrut(5));
    add(combobox);
    add(Box.createRigidArea(new Dimension(320,5)));
    setBorder(BorderFactory.createEmptyBorder(5,5,0,5));
  }
  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;
    }
    public String toString() {
      return item;
    }
    public boolean hasSeparator() {
      return flag;
    }
  }
以下省略
  • &jnlp;
  • &jar;
  • &zip;

解説

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

参考リンク

コメント