Search code examples
javaswingjtabletablecellrenderer

Java swing cell renderer based on column class


In Java Swing we have a JTable, TableModel, ColumnModel and a TableCellRenderer which work together to display a table.

How can I provide customisation to get a custom cell renderer based on a column class - as opposed to setting the renderer based on column index.

final JTable table = new JTable(model);
table.getColumnModel().getColumn(0).setCellRenderer(new DateTimeRenderer());
table.getColumnModel().getColumn(1).setCellRenderer(new SuperDuperDoubleCellRenderer());

Suppose I have 20 numeric cells in there!!!

The above works, but I am not so keen on that solution as it would change when the model changed - so it isn't well encapsulated to that extent - this is client code.

The TableModel understands the underlying table data structure where it can do the custom mapping to a complex type (as opposed to DefaultTableModel and Vectors) - where it knows the data types of how each column.

public class DemoTableModel implements TableModel {
    @Override
    public Class<?> getColumnClass(int columnIndex) {
        // date time, double, etc...
        return columnInfo.get(columnIndex).getDataType();
    }
}

What I would like to do is to tell a JTable, hey the column class (returned from the table model) is a custom DateTime type - use the CustomDateTimeCellRenderer. If it is a double, then use the custom SuperDuperDoubleCellRenderer.

The trouble is digging through the sources to see where this behaviour marries up.


Solution

  • What I would like to do is to tell a JTable, hey the column class (returned from the table model) is a custom DateTime type - use the CustomDateTimeCellRenderer. If it is a double, then use the custom SuperDuperDoubleCellRenderer.

    You set the renderer at the table level by specifying the class and renderer:

    table.setDefaultRenderer(Double.class, yourDoubleCellRenderer);
    table.setDefaultRenderer(CustomDateTime.class, yourCustomDateTimeRenderer);