Java Reference
In-Depth Information
When it's time to draw each cell, the interface's sole method is called. The returned
renderer provides the specific rendering for that one cell of the
JList
. The
JList
uses the
rendering to draw the element, and then gets the next renderer.
A reference to the enclosing
JList
is provided to the
getListCellRendererComponent()
method so that the renderer can share display characteristics. The
value
of the selection
contains the object in the list's data model at position
index
. The index is zero-based from the
beginning of the data model. The last two parameters allow you to customize the cell's appear-
ance based on the cell's state—that is, whether it's selected or has the input focus.
Listing 13-4 shows a renderer that demonstrates this technique. The sole difference for
this renderer is that the cell with the input focus has a titled border. After the renderer is
created, you install it by setting the
cellRenderer
property of the
JList
.
■
Tip
For performance reasons, it is best not to create the actual renderer in the
getListCellRendererComponent()
method. Either subclass
Component
and return
this
or
create a class variable to hold one instance of a
Component
, which then may be customized and returned.
Listing 13-4.
Rendering the List Cells
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class FocusedTitleListCellRenderer implements ListCellRenderer {
protected static Border noFocusBorder =
new EmptyBorder(15, 1, 1, 1);
protected static TitledBorder focusBorder =
new TitledBorder(LineBorder.createGrayLineBorder(), "Focused");
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
public String getTitle() {
return focusBorder.getTitle();
}
public void setTitle(String newValue) {
focusBorder.setTitle(newValue);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel renderer = (JLabel)defaultRenderer.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
renderer.setBorder(cellHasFocus ? focusBorder : noFocusBorder);
return renderer;
}
}