Java Reference
In-Depth Information
Listing 18-2. Custom Table Cell Renderer
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class EvenOddRenderer implements TableCellRenderer {
public static final DefaultTableCellRenderer DEFAULT_RENDERER =
new DefaultTableCellRenderer();
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component renderer =
DEFAULT_RENDERER.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
Color foreground, background;
if (isSelected) {
foreground = Color.YELLOW;
background = Color.GREEN;
} else {
if (row % 2 == 0) {
foreground = Color.BLUE;
background = Color.WHITE;
} else {
foreground = Color.WHITE;
background = Color.BLUE;
}
}
renderer.setForeground(foreground);
renderer.setBackground(background);
return renderer;
}
}
Renderers for tables can be installed for individual classes or for specific columns (see the
“Enabling the Default Table Cell Renderers” section later in this chapter for details). To install
the renderer as the default renderer for the JTable —in other words, for Object.class —use code
similar to the following:
TableCellRenderer renderer = new EvenOddRenderer();
table.setDefaultRenderer(Object.class, renderer);
Once installed, the EvenOddRenderer will be used for any column whose class doesn't have
a more specific renderer. It's the responsibility of the public Class getColumnClass() method
of TableModel to return the class to be used as the renderer lookup for all the cells in a particular
column. The DefaultTableModel returns Object.class for everything; therefore, EvenOddRenderer
will be used by all table cells.
Search WWH ::




Custom Search