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()
I had multiple tables, so I created a method to clear "any" table:
private void deleteAllTableRows(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
while( model.getRowCount() > 0 ){
model.removeRow(0);
}
}
Well, setNumRows(0) should work, although if you actually read the API it tells you that this method is obsolete and tell you which method to use instead.
If the code doesn't work, then you are doing something else wrong and we can't tell from the posted code what that might be.
Post your SSCCE that demonstrates the problem.
Read the API for DefaultTableModel - setRowCount method supports deleting/discarding all rows in one go...
((DefaultTableModel)myTable.getModel()).setRowCount(0);
Or if you have lots of rows but very few columns...
DefaultTableModel dtm = new DefaultTableModel();
for(int i=0;i<NUM_COLS;i++) dtm.addColumn(COLUMN_NAME[i]);
myTable.setModel(dtm);
...replaces the old DTM with a fresh one.
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.
Try this code. This will remove all the rows from JTable.
DefaultTableModel model=new DefaulTableModel(rows,cols);
JTable table=new JTable(model);
for(int i=0;i<model.getRowCount();i=i+0)
{
model.removeRow(0);
revalidate();
}