Search code examples
javajtabletablemodel

Exception in implementing AbstractTableModel in JAVA?


I have implemented a custom Table Model as follows:

public class MyTableModel extends AbstractTableModel {
    ...
    ...
    @Override
    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }
    ...
    ...
}

I am getting NullPointerException thrown by the above method, when I display a JTable having the above TableModel.

I think that the exception is due to some empty cells in the database table.

If the exception is due to empty cells in the database table, then how to get around with this problem?

It is not mandatory for every column in the database to have some value. Some columns can contain nothing.


Solution

  • If cells can contain empty values, then calling getClass() on a null value will certainly give you the NPE. Sure you can check for null, but your real problem is more subtle than that.

    The TableModel interface specifies that getColumnClass(int) should return "the most specific superclass for all the cell values in the column." From the looks of things, you could be returning any number of class types for a single column, effectively breaking the TableModel contract.

    Typically, column types are static for a given set of table data, meaning the class for a column shouldn't change unless the underlying table data has changed. I think it's important to ask why you need to return such a specific value.

    In the case where you want to render something specific for a given class type, you're better off rolling your own TableCellRenderer, and determining the Object type on a per-cell basis. From there you can do any specific rendering as needed.