Question

I am new to Swing framwork. And I have the following list to design..

enter image description here

Is there any way by which we can have customized list items in JList? Like writing custom Adapter in Android, which has a method getView() which will return the View to be shown as ListItem...

Was it helpful?

Solution

You're going to need a custom renderer. You can either use a DefualtListCellRenderer which uses a JLabel as the rendering component, or you can create a custom ListCellRenderer where you can specify the rendering the component by extending the component and impelenting ListCellRenderer.

You can see more Providing a Custom Renderer. The link is to the "How to Use Comboboxes" tutorial, but comboboxes and JLists use the same type renderer.

The basic concept you will find is that you will have to override the method

public Component getListCellRendererComponent(
                                   JList list,
                                   Object value,
                                   int index,
                                   boolean isSelected,
                                   boolean cellHasFocus) {

for either a custom ListCellRenderer or for a DefaultListCellRenderer. The Value will return the value of each list item. A list item can be an object, say a Person with fields id and name. So you would case the value to Person and use the necessary fields to render the component.

Person person = (Person)value;
// renderer the component using Person values
// lastly return the component.

So basically just break it down to "how would you renderer one of the cells?" What components would you use? Then just implement the renderer class/method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top