O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Rendering Cells

You can build your own renderers for the cells in your table. By default, you get renderers for Boolean types (JCheckBox for display and editing), ImageIcon types, Number types (right-justified JTextField), and Object types (JTextField). However, you can specify a particular renderer for a class type or for a particular column, or even for a particular cell.

The TableCellRenderer Interface

This interface provides access to a rendering component without defining what the component does. This works because a renderer functions by rubber-stamping a component’s image in a given location. The only method this interface defines initializes and returns just such a component:

public abstract Component getTableCellRendererComponent(JTable table, Objectvalue, boolean isSelected, boolean hasFocus, int row, int column)

This model takes a value, which can also be retrieved by getting the cell at row, column of table, and returns a component capable of drawing the value in a table cell (or anywhere, really). The resulting drawing can be affected by the selection state of the object and whether it currently has the keyboard focus.

The DefaultTableCellRenderer Class

The javax.swing.table package includes a default renderer that produces a JLabel to display text for each cell in the table. The JTable class uses this renderer to display Numbers, Icons, and Objects. JTable creates a new default renderer and then aligns it correctly and attaches an appropriate icon, depending on the type ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required