<$BlogRSDUrl$>

Fuzzy Space

Two Confused Minds, One Eye-Opener.

Friday, April 14, 2006

HOWTO: Java Swing Custom TableCellRenderer.

Great apologies to everyone (or anyone at all ;op) who had long awaited for my first tech entry. More importantly, apologies to my co-contributor of this blog. She has done much more for this blog than me! Thanks! ;o> The first entry is always difficult. I am not sure whether the topic is too basic. However, I will try to keep my entries short and simple, as I think whoever finds it useful like the important points to be clearly presented. The first topic I am going to cover is a common Swing component, JTable. Typically, JTables are used to display data. The Sun Java Tutorial is a great source of information on how to accomplish some common table-related tasks. One of the key feature of JTable is the default cell renderer. There is an automatic mapping between the column class type and the predefined cell renderer used. For example, a Boolean class type data will be displayed as a JCheckBox, which is more intuitive than displaying the words "true" or "false". All you need is to do is to override the getColumnClass in your TableModel class. The code snip below shows an example of the overridden class.
Below is a simple table from the Java Tutorial that is implemented using the default renderer. The Boolean "vegetarian" column is rendered as a JCheckBox. However, if you noticed, the columns are all of same size and text aligned to the left.
In order to fix this problem, you'll need to use a custom table cell renderer in which you can specify the horizontal alignment. You'll probably use the DefaultTableCellRenderer to do the job. The following code snip shows how,
Be sure to set the default renderer to your custom renderer or turn off the auto-create-column option. Otherwise, you'll have twice the number of columns, one by the default renderer and one by your custom renderer.
This works fine for String columns, but you'll realise the predefined renderers are not used. A Boolean column will be displayed as "true" or "false", instead of a JCheckBox. This is because the "default cell renderer" is not "DefaultTableCellRenderer". Therefore you'll actually need to write your own custom renderer to display the cells the way you want. The trick to writing a custom renderer class is to either extend from the DefaultTableCellRenderer or extend the component class you want to render and implement the TableCellRenderer class, then override the getTableCellRendererComponent method. Using the same method, you can also define color to render the cell.
Below are some useful resources you need to construct your perfect JTable, IBM Developer Article: Rendering cells in Swing's JTable component Javadoc: JTable Java Tutorial: How to Use Tables Sample Code from CSUN: TableDemo with Custom TableCellRenderers Hope that you find this entry useful! :o>

Archives

website statistics