<java 设计模式>里面的一段Each cell in a table is rendered by a cell renderer. The default
renderer is a JLabel, and it may be used for all the data in several columns.
Thus, these cell renderers can be thought of as Flyweight pattern
implementations. The JTable class chooses the renderer accoring to the object’s type as we outlined above. However, you can change to a different rendered, such as one that uses another color, or another visual interface quite
easily.
Cell renderers are registered by type of data:
table.setDefaultRenderer(String.class, new ourRenderer());
and each renderer is passed the object, selected mode, row and column using
the only required public method:
public Component getTableCellRendererComponent(JTable jt,
Object value, boolean isSelected,
boolean hasFocus, int row, int column)
One common way to implement a cell renderer is to extend the
JLabel type and catch each rendering request within the renderer and return a
properly configured JLabel object, usually the renderer itself. The renderer
below displays cell (1,1) in boldface red type and the remaining cells in plain,
black type:
public class ourRenderer extends JLabel
implements TableCellRenderer
{
Font bold, plain;
public ourRenderer() {
super();
setOpaque(true);
setBackground(Color.white);
bold = new Font("SansSerif", Font.BOLD, 12);
plain = new Font("SansSerif", Font.PLAIN, 12);
setFont(plain);
}
//-------------------------------------------------------
public Component getTableCellRendererComponent(JTable jt,
Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
setText((String)value);
if(row ==1 && column==1) {
setFont(bold);
setForeground(Color.red);
}
else {
setFont(plain);
setForeground(Color.black);
}
return this;
}
}
In the simple cell renderer shown above the renderer is itself a JLabel which returns a different font, but the same object, depending on the row and column. More complex renderers are also possible where one of several already-instantiated objects is returned, making the renderer a Component Factory.