TITLE:JComboBoxのアイテムをBorderで修飾してグループ分け
#navi(../)
*JComboBoxのアイテムをBorderで修飾してグループ分け [#zb21cb91]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2005-09-20~
更新日:&lastmod;

#contents

**概要 [#n40caa06]
JComboBoxのアイテムをBorderを使用して修飾してグループ分けします。

[[プログラム板 Java低速GUI Swing 3>http://pc8.2ch.net/test/read.cgi/tech/1121700954/]]の229さんのアイデアを参考にしています。

#screenshot

**サンプルコード [#x381b337]
#code{{
 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;

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

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

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