Search code examples
javaswingjtableselectiondefaulttablemodel

how to use convert model of Jtable


I have a jTable and I want to delete selected rows:

   for( int i=0; i<selectedRows.length ; i++){                  
        defaultablemodel.removeRow( selectedRows[i] - i);
        int viewRowIndex = jTableMyTable.convertRowIndexToView(i); <<--- convert it here?
   }

I searched around and most suggestions whenever delete rows, we should convert row index to view. Is the above correctly implemented? I hit this problem because after i sorted my rows, i am unable to delete the row sometimes. but after sorting again i am able to delete a row. So i believe I need to use this convertRowIndexToView method.


Solution

  • You should actually be using

    • convertRowIndexToModel - Maps the index of the row in terms of the view to the underlying TableModel. If the contents of the model are not sorted the model and view indices are the same.

    You have your selected rows, which are the selected indices in the view. So you need to convert those indices to the model indices before deleting.

    When you use convertRowIndexToView, you're actually doing the opposite, trying to convert the model index to the table index.

    " Is the above correctly implemented?"

    First thing, when you want to remove rows this way, you should be traversing the indices backwards, from the last row up. The reason is that when you remove a row, the indices change. So you loop should go backwards like

    int [] selectedRows = table.getSelectedRows();
    for (int i = selectedRows.length - 1; i >= 0; i--) {
        int viewIndex = selctedRows[i];
        int modelIndex = table.convertRowIndexToModel(viewIndex);
        model.removeRow(modelIndex);
    }
    

    The point is you want to remove the highest index first and work your way down to the lower indices.