• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JComboBoxのアイテムをBorderで修飾してグループ分け
#navi(../)
*JComboBoxのアイテムをBorderで修飾してグループ分け [#zb21cb91]
Posted by [[terai]] at 2005-09-20

#contents

**概要 [#n40caa06]
JComboBoxのアイテムをBorderを使用して修飾してグループ分けします。[[プログラム板 Java低速GUI Swing 3>http://pc8.2ch.net/test/read.cgi/tech/1121700954/]]の229さんのアイデアを参考にしています。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#x381b337]
#code{{
final JComboBox combobox = new JComboBox();
final JSeparator sep = new JSeparator();
final ListCellRenderer lcr = combobox.getRenderer();
combobox.setRenderer(new ListCellRenderer() {
public Component getListCellRendererComponent(
  public Component getListCellRendererComponent(
               JList list, Object value, int index,
               boolean isSelected, boolean cellHasFocus) {
  MyItem item = (MyItem)value;
  JLabel label = (JLabel)lcr.getListCellRendererComponent(
    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));
    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);
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));
}}

#code{{
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;
  }
}
//......
}}

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

コンボボックスが編集可の場合は、フィールド表示にはレンダラーではなく、JTextFieldが使用されるため、[[JComboBoxにJSeparatorを挿入>Swing/ComboBoxSeparator]]する方法より簡単に区切りを表現することができます。

**参考リンク [#w4c1b8bb]
-[[プログラム板 Java低速GUI Swing 3>http://pc8.2ch.net/test/read.cgi/tech/1121700954/]]
-[[JComboBoxにJSeparatorを挿入>Swing/ComboBoxSeparator]]

**コメント [#f99d5b78]
#comment