TableCellRenderer, Part 1 - The Basics(11:00, 30. Jul. 2010)

As you maybe know a TableCellRenderer is an interface with a single method which returns a component - the returned component is used for rendering table data.

public interface TableCellRenderer 
{
  Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, 
                                          boolean hasFocus, int row, int column);
}

Swing's default implementation is DefaultTableCellRenderer and is based on JLabel - simply because a label is good enough to display most kind of data. The default renderer returns itself as cell renderer component. For customization it's helpful to keep in mind that the default renderer component is a JLabel instance.

JTable provides a method which allows you to install different renderers for different classes. This means you can specify a renderer for i.e. String objects, Number objects and of course for your own custom data objects.

JTable#setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer)

When you specify a renderer for a class, the renderer will be only called if the registered class matches with the related column data class. Generally a table creates and registers a bunch of renderers under the hood so you won't get bothered with specifying renderers for simple tables. The most generic types of renderers take care of the classes Object and Boolean.

Additional renders for the classes Number, Float, Double, Icon, ImageIcon, and Date will be additionally created. These renderers are derived from DefaultTableCellRenderer. Note: A Synth based look and feel, by default, installs renderers for Object and Boolean classes only. In Synth the default renderer (for Object classes) also takes care about rendering the mentioned classes (Number, Float...) in a specific manner.

So technically the main difference by using a Synth based look and feel is that a maximum of two renderer instances (Object, Boolean) are responsible for cell rendering by default. Keep this fact in mind if you have to create a custom renderer. In Synthetica releases above 2.10.1 you can modify this behavior - by default Synthetica behaves as intended by Synth.

JTable also allows you to specify renderers for particular columns through a TableColumn. A table column can be accessed by JTable#getColumnModel().getColumn(columnIndex).

TableColumn#setCellRenderer(TableCellRenderer cellRenderer)

The next article explains how to create and use a custom renderer and what you have to consider.