Terai Atsuhiro 2021-02-21 (日) 03:52:16

http://terai.xrea.jp/swing/comboboxseparator/screenshot.png

final ListCellRenderer lcr = combobox.getRenderer();
combobox.setRenderer(new ListCellRenderer() {
  public Component getListCellRendererComponent(JList list, Object value,
                    int index, boolean isSelected, boolean cellHasFocus) {
    if(value instanceof JSeparator) {
      return (JSeparator)value;
    }else{
      return (JLabel)lcr.getListCellRendererComponent(
                  list,value,index,isSelected,cellHasFocus);
    }
  }
});
DefaultComboBoxModel model = new DefaultComboBoxModel() {
  public void setSelectedItem(Object anObject) {
    if(!(anObject instanceof JSeparator)) {
      super.setSelectedItem(anObject);
    }
  }
};
model.addElement("aaaa");
model.addElement(new JSeparator());
model.addElement("bbb1");
combobox.setModel(model);
  • ListCellRenderer
  • DefaultComboBoxModel
combobox.addItemListener(new ItemListener() {
  private Object prev;
  public void itemStateChanged(ItemEvent e) {
    if(e.getStateChange()==ItemEvent.SELECTED) {
      Object obj = e.getItem();
      if(obj instanceof JSeparator) {
        if(prev==null) prev = combobox.getItemAt(0);
        combobox.setSelectedItem(prev);
      }else{
        prev = obj;
      }
    }
  }
});

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;
  }
}