How do I add a separator to a JComboBox in Java?

Alfred B. Thordarson picture Alfred B. Thordarson · Sep 26, 2008 · Viewed 10.5k times · Source

I have a JComboBox and would like to have a separator in the list of elements. How do I do this in Java?

A sample scenario where this would come in handy is when making a combobox for font-family-selection; similar to the font-family-selection-control in Word and Excel. In this case I would like to show the most-used-fonts at the top, then a separator and finally all font-families below the separator in alphabetical order.

Can anyone help me with how to do this or is this not possible in Java?

Answer

pfranza picture pfranza · Sep 26, 2008

There is a pretty short tutorial with an example that shows how to use a custom ListCellRenderer on java2s http://www.java2s.com/Code/Java/Swing-Components/BlockComboBoxExample.htm

Basically it involves inserting a known placeholder in your list model and when you detect the placeholder in the ListCellRenderer you return an instance of 'new JSeparator(JSeparator.HORIZONTAL)'