Search code examples
javaswingjtabledefaulttablemodelabstracttablemodel

Removing a row from a JTable using AbstractTableModel


I have a JTable. This table is using a custom model that I designed; the custom model is extends AbstractTableModel. I have a button which enables a user to delete a selected/highlighted row.

I have tried this code but its giving me a class cast exception -

myTableModel cannot be cast to DefaultTableModel. 

Below is the code.

DefaultTableModel model =  (DefaultTableModel)table.getModel();
        model.removeRow(table.convertRowIndexToModel(table.getSelectedRow()));
        model.fireTableDataChanged();`

I have searched the web but it is always DefaultTableModel - but I have AbstarctTableModel.

How do we solve this?


Solution

  • I have tried this code but its giving me a class cast exception - myTableModel cannot be cast to DefaultTableModel.

    The error is pretty self-explanatory: given you provide the table with your own table model, then table.getModel() won't ever return a DefaultTableModel instance.

    How do we solve this?

    By down-casting table.getModel() to the appropriate class (your class). Then call the method you provided to remove a row from your table model. For example:

    int modelRowIndex = table.convertRowIndexToModel(table.getSelectedRow());
    MyTableModel model = (MyTableModel)table.getModel();
    model.removeRowFromMyModel(modelRowIndex);
    

    See a complete example of a custom table model extending from AbstractTableModel in this question.

    Off-topic

    We never should call any of fireXxx() methods explicitely from the outside. Those are intended to be called internally by AbstractTableModel subclasses when needed. IMHO those should be protected and not public, to avoid use them incorrectly. But for some reason I'm not aware of they made them public.