Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Sep 5, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Dividing a JList

Normally, a list of items in a Java application is presented in a JList or JComboBox. If all of the listed items are created equally, the list handles them quite nicely. However, when you want to organize your list items in groups, there's no obvious way to do so without using a JTree.

However, inserting dividing lines into your JList or JComboBox (which normally uses a JList as the dropdown component) isn't so difficult.

Create a ListCellRenderer component for your list. You can do this by implementing the sole required method of the ListCellRenderer interface, or by extending the DefaultListCellRender class. However you do it, the principle is the same. Each time the list items are drawn, the renderer method getListCellRendererComponent( ) is called to obtain a component to be used as a visual template for the list item. To get dividing lines or separators to be drawn, you will need first to ensure that your list model contains items that represent the divider lines. When those items are encountered, simply return a component that looks like a dividing line. The following sample method shows the technique applied to list items that have an underscore as their toString( ) return value.
public Component getListCellRendererComponent(JList 
list, Object value, int
index, boolean isSelected, boolean cellHasFocus) {
	if ( value != null && value.toString( ).equals
("_") )
		JLabel lblSeparator = new JLabel( );
BorderFactory.createLineBorder(Color.black ) );
		lblSeparator.setPreferredSize( new 
Dimension( 2, 2 ) );
		return lblSeparator ;
		return super.getListCellRendererComponent
( list, value,
index, isSelected, cellHasFocus);

The key here is to use setPreferredSize( ) to fix the row height at 2 pixels. This size is only used when the list is initially laid out. After that, the row height can't be changed as easily. The label border draws the black line separator. Set the list cell renderer using list.setCellRenderer() for JLists and combo.setRenderer( ) for JComboBoxes.
Andy Brundell
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date