Removing all the rows of DefaultTableModel

Xara picture Xara · May 2, 2012 · Viewed 36.9k times · Source

I want to delete all the rows of DefaultTable. I found two common ways to delete them on internet, but none of them works in my case because those methods does not exist in my DefaultTableModel. I wonder why. My code for using DefaultTableModel is

DefaultTableModel Table = (DefaultTableModel) Table.getModel();

One way to delete is

Table.removeRow(Table.getRowCount() - 1);

but this removerow method does not exist in my DefaultTableModel.

Answer

Mattias Isegran Bergander picture Mattias Isegran Bergander · May 2, 2012

You can set the row count to 0. setRowCount(0)

Quote from 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.

But as you can't find removeRow either I suspect you haven't typed you model variable as DefaultTableModel perhaps, maybe just TableModel?

In that case cast your TableModel to DefaultTableModel like this:

DefaultTableModel model = (DefaultTableModel) table.getModel();