Icon Table Cell Renderer
Posted by Darryl Burke on December 18, 2008
The suplied default renderer for JTable columns of class Icon and ImageIcon, JTable.IconRenderer, is known to give rise to a ClassCastException when attempting to render an Icon whose implementation of paintIcon(…) requires a cast of its Component parameter to a specific subclass of Component. Several icons obtained from standard JDK classes trigger this ClassCastException.
IconTableCellRenderer addresses this issue by attempting to paint the Icon in 3 different ways before falling back on a default icon which can be customized via a parameter to the constructor.
- First, an attempt is made to paint the Icon to the Graphics context of a BufferedImage with a reference to the renderer itself as the Component parameter.
- In case of a ClassCastException, the desired class is identified by parsing the exception’s message. An attempt is made to instantiate a Component of the desired class and use it as a valid reference.
- In case an InstantiationException is thrown because the desired class is abstract, a final attempt is made to draw the icon with a concretized AbstractButton furnished with a DefaultButtonModel as the Component parameter.
- All else failing, the icon is rendered as a crossed rectangle of the same size as the original icon, or the default icon if supplied as a parameter to the constructor.
Using IconTableCellRenderer is no different from using any custom renderer.
table.setDefaultRenderer(Icon.class, new IconTableCellRenderer());
This is a view of some of the default Metal L&F icons as rendered by IconTableCellRenderer
IconTableCellRenderer extends DefaultTableCellRenderer.
Get The Code
The Java™ Tutorials: How to Use Tables: Using Custom Renderers