Deleting all the rows in a JTable

Something like this should work

DefaultTableModel model = (DefaultTableModel)this.getModel(); 
int rows = model.getRowCount(); 
for(int i = rows - 1; i >=0; i--)
{
   model.removeRow(i); 
}

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);
}

We can use DefaultTableModel.setRowCount(int) for this purpose, refering to Java's Documentation:

public void setRowCount(int rowCount)

Sets the number of rows in the model. If the new size is greater than the current size, new rows are added to the end of the model If the new size is less than the current size, all rows at index rowCount and greater are discarded.

This means, we can clear a table like this:

DefaultTableModel dtm = (DefaultTableModel) jtMyTable.getModel();
dtm.setRowCount(0);

Now, on "how does java discard those rows?", I believe it just calls some C-like free(void*) ultimately somewhen, or maybe it just removes all references to that memory zone and leaves it for GC to care about, the documentation isn't quite clear regarding how this function works internally.


Read the API for DefaultTableModel - setRowCount method supports deleting/discarding all rows in one go...

((DefaultTableModel)myTable.getModel()).setRowCount(0);

Tags:

Java

Swing

Jtable