Sparrow7000
Sparrow7000

Reputation: 79

How to delete all rows of a JTable in Loop?

I am trying to delete all rows of my JTable when an action is performed.

I wrote code below:

DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    int rowCount = model.getRowCount();
    for (int i = 0; i < rowCount ; i++){
        model.removeRow(i);
    }

But it didn't work as I expected.

Upvotes: 1

Views: 1320

Answers (2)

Sparrow7000
Sparrow7000

Reputation: 79

I searched the net and find out that we should delete the rows of the table from the end of the table instead of the beginning. I wanted to share this information with others.

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

It worked properly for me. Good Luck.

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347184

Each time you remove a row, the row count will change. Better to continue looping until there are no rows left

while (model.getRowCount() > 0) {
    model.removeRow(0);
}

Now, if I'm not wrong, you could also just do model.setRowCount(0) and it will remove all the rows for you ;)

Upvotes: 4

Related Questions