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