Extend Swing’s JTable to Support Rendering of Different Cell Types in a Column

The basic JTable rendering mechanism supports a single renderer for all cells in a column. The Column Renderer may be set in the TableColumn class. If the TableColumn Renderer is null, the JTable looks up the Renderer based on the Column Class. The Column Class is then determined by the TableModel getColumnClass() method.

Both these approaches assume all values in a column are of the same type, prohibiting the rendering of cell values of different types in a column

To extend the JTable to support the display of cells of different types in one column, sublass JTable. Then, override the getCellRenderer() method to look up the appropriate renderer at run-time, based on the type of the value in the cell.

public class JMyTable  extends JTable{ public TableCellRenderer getCellRenderer(int row, int column) {  Object value = getValueAt(row,column);  if (value !=null) {    return getDefaultRenderer(value.getClass());  }  return super.getCellRenderer(row,column); }};
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: