How do you remove selected rows from a JTable?

Penchant picture Penchant · Mar 17, 2009 · Viewed 54.6k times · Source

I've tried this:

public void removeSelectedFromTable(JTable from)
{
    int[] rows = from.getSelectedRows();
    TableModel tm= from.getModel();

    while(rows.length>0)
    {
        ((DefaultTableModel)tm).removeRow(from.convertRowIndexToModel(rows[0]));

        rows = from.getSelectedRows();
    }
    from.clearSelection();
}

But, it sometimes leaves one still there. What can be the problem?

Answer

Alejandro picture Alejandro · Jan 30, 2011

It doesn't work, this is better:

public void removeSelectedRows(JTable table){
   DefaultTableModel model = (DefaultTableModel) this.table.getModel();
   int[] rows = table.getSelectedRows();
   for(int i=0;i<rows.length;i++){
     model.removeRow(rows[i]-i);
   }
}