Table Format Renderers
Posted by Rob Camick on October 11, 2008
JTable uses renderers to display data in each cell of the table. This allows for data to easily be displayed in different formats in any given cell. However, the table only provides support for a few basic renderers:
- Boolean – rendered with a check box.
- Number – rendered by a right-aligned label .
- Date – rendered by a label.
- Icon – rendered by a centered label.
- Object – rendered by a label that displays the object’s string value.
Not much to choose from when you want to jazz up the display of your data. Fortunately we can easily create a renderer which will allow us to format the data in various ways.
Most code examples of custom rendering show code that overrides the getTableCellRendererComponent(…) method to update the properties of the renderer directly. For simple formatting we will take a different approach, as we will be overriding the setValue(…) method. Using this approach we can take advantage of the Format class and the formatting capabilities of its sub classes, specifically the DateFormat and NumberFormat classes.
The FormatRenderer will require only a single parameter, the Format object to be used to format the data. For example:
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd");
TableCellRenderer renderer = new FormatRenderer( format );
A convenience class, NumberRenderer, was also created that simply uses right alignment for the renderer. In both classes, convenience static methods where created to return common renderers. The breakdown is as follows:
The following code sample was used to generate the table pictured in the image:
TableColumnModel m = table.getColumnModel();