Search code examples
javaswingjtable

Deleting all the rows in a JTable


I need to remove all the rows in my JTable.

I have tried both of the following:

/**
 * Removes all the rows in the table
 */
public void clearTable()
{
    DefaultTableModel dm = (DefaultTableModel) getModel();
    dm.getDataVector().removeAllElements();
    revalidate();
}

and

((DefaultTableModel)table.getModel()).setNumRows(0);

Neither of which would remove all the rows. Any ideas?


Solution

  • The following code worked for me:

    DefaultTableModel dm = (DefaultTableModel) getModel();
    int rowCount = dm.getRowCount();
    //Remove rows one by one from the end of the table
    for (int i = rowCount - 1; i >= 0; i--) {
        dm.removeRow(i);
    }