You have to apply the ListCellRenderer to all elements in the list, but that does not mean it has to render all of them in the same way. For example, you could render a cell based on its value (either the raw value or even just based on the value's class, or even based on the cell's index:
package com.example;
import java.awt.Color;
import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class ListCellRendererExample extends JFrame {
public ListCellRendererExample() {
DefaultListModel model = new DefaultListModel();
model.addElement(Color.BLUE);
model.addElement("hello");
model.addElement(5);
model.addElement(Color.RED);
JList jlist = new JList(model);
jlist.setCellRenderer(new SuperDuperListCellRenderer());
add(new JScrollPane(jlist));
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationByPlatform(true);
setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
new ListCellRendererExample();
}
private static class SuperDuperListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
// If the value is a color, give the cell a blank value but save its
// value so we can later change its background to the value's color.
Color bgColor = null;
if (value instanceof Color) {
bgColor = (Color) value;
value = " ";
}
// Prepend the index to the "even" rows (the first row is row 1)
if ((index + 1) % 2 == 0) {
value = index + ": " + value;
}
Component renderComponent = super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
// If the value is a color, set the cell's background to that color.
if (bgColor != null) {
renderComponent.setBackground(bgColor);
}
return renderComponent;
}
}
}