deleting rows from a JTable
I know that you can call this method to delete a row from a JTable:
DefaultTableModel.deleteRow(index);
I need to delete all of the rows at some point, and this is not working:
for (int i=0; i<dtm.getRowCount(); i++)
{
dtm.removeRow(i);
mortgageTable.revalidate();
}
I tried revalidating, but that didn't work. This only deletes the last row. Now, at runtime the table consists of only one row and later many rows are added. So I'm thinking the DefaultTableModel is not picking up the newly added rows.
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
Think of what you're doing and you get the idea quickly enough.
You delete row 0, then increase i to 1, then move to the next row (which is the old row 2).
Then you delete row 1, increase i to 2, move to the next row.
If you want to do something like this, start at the end and delete from there to the front.
Something like
int numRows == dtm.getRowCount();
for (int i=numRows;i>=0;i++) {
dtm.removeElement(i);
mortgageTable.revalidate();
}
should give you the results you are looking for.
jwenting
duckman
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
WOW! I would have NEVER spoted that. I was thinking since it ran at runtime with only one row that it never updated the count. Thank you so much; I was banging my head against the wall on this one...I wish I could give you a big hug for that. :lol:
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
I've banged my head against the wall more than once over the same problem, but finally the solution stuck in my head :)
jwenting
duckman
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
Original post was three years ago. I doubt they still need help. Read the dates before posting.
jasimp
Senior Poster
3,623 posts since Aug 2007
Reputation Points: 533
Solved Threads: 53
This is more efficient way:
//deletes ALL the rows
DefaultTableModel.getDataVector().removeAllElements();
//repaints the table and notify all listeners (only once!)
DefaultTableModel.fireTableDataChanged();
If you do this
while (mortgageTable.getRowCount() > 0) {
((DefaultTableModel) mortgageTable.getModel()).removeRow(0);
}
This will fire notificantions to all the listeners everytime you delete one row, so, if you have 100000 rows........
let me guess ... your clock stopped in the past too?
stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433