Java Reference
In-Depth Information
Creating a Complex ListCellRenderer
More often than not, custom cell renderers (like the one shown in Figure 13-6) are necessary
when the data model consists of more complex data in each element—something not repre-
sentable by a text string. For instance, Listing 13-6 shows the source for an example where each
element of the data model consists of a font, foreground color, icon, and text string. Ensuring
the proper usage of these elements within the renderer simply involves a little more work in
configuring the renderer component. In this particular example, that data is stored within each
element of an array in the data model. You could just as easily define a new class or use a
hash table.
Listing 13-6. Rendering Complex List Cells
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class ComplexCellRenderer implements ListCellRenderer {
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
Font theFont = null;
Color theForeground = null;
Icon theIcon = null;
String theText = null;
JLabel renderer = (JLabel)defaultRenderer.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
if (value instanceof Object[]) {
Object values[] = (Object[])value;
theFont = (Font)values[0];
theForeground = (Color)values[1];
theIcon = (Icon)values[2];
theText = (String)values[3];
} else {
theFont = list.getFont();
theForeground = list.getForeground();
theText = "";
}
if (!isSelected) {
renderer.setForeground(theForeground);
}
if (theIcon != null) {
renderer.setIcon(theIcon);
}
Search WWH ::




Custom Search