devxlogo

Dividing a JList

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, intindex, boolean isSelected, boolean cellHasFocus) {	if ( value != null && value.toString( ).equals("_") )	{		JLabel lblSeparator = new JLabel( );		lblSeparator.setBorder( BorderFactory.createLineBorder(Color.black ) );		lblSeparator.setPreferredSize( new Dimension( 2, 2 ) );		return lblSeparator ;	}	else		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.

See also  Comparing different methods of testing your Infrastructure-as-Code
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist