Deleting all the rows in a JTable
Asked Answered
M

15

33

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()
{
    DefaultTableModel dm = (DefaultTableModel) getModel();
    dm.getDataVector().removeAllElements();
    revalidate();
}

and

((DefaultTableModel)table.getModel()).setNumRows(0);

Neither of which would remove all the rows. Any ideas?

Minetta answered 3/6, 2011 at 20:31 Comment(6)
@MByD I just added revalidate(), but still seeing the same thing. I am using a CustomeTableCellRenderer, but wouldnt think that would do too much.Minetta
I tried this as well. No luck. I think there is something else going on.Minetta
@MByD, no you shouldn't revalidate() or repaint(). The TableModel is responsible for notifying the JTable that something has changed so the table can repaint itself automatically.Petra
@Petra - that for the information :)Induction
voting to close as not-a-real-question - it's not answerable as posted, and evokes one incorrect pseudo-answer after another ...Anus
check if [this][1] this solves your problem [1]: https://mcmap.net/q/281253/-deleting-datas-in-the-table-in-guiOutlive
P
41

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);
}
Pottage answered 3/6, 2011 at 20:39 Comment(7)
-1, Actually, this code doesn't work. First you remove row 0, then all the rows shift down 1. Then you delete row 1, which means row 0 is still there. James_Bond's answer shows how this is done by deleting from the end not the start.Petra
Yes, you're right, the array elements have to be removed from back to front.Pottage
no need for looping - DefaultTableModel has api to clear all rows with a single method call ...Anus
Wondering how this code can work with the i++. Should probably be i--Lylalyle
It doesn't work, it will only delete half of the table, and throw an exception after that. You could replace i inside the loop with 0.Dacoit
Check the updated version. The idea is to remove rows from the end of the table.Pottage
((DefaultTableModel) jtMyTable.getModel()).setRowCount(0)Contentious
B
93

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.

Barbarian answered 26/3, 2013 at 12:2 Comment(4)
Great and simple code. Although the flagged answer to this question is also correct, it has problem when it comes on deleting thousands of rows. If you're handling thousands of row, this code is a snap.Steamship
This one clear all table rows. Easy and usable. ThanksIrresponsible
This is the best answer.Brann
Best answer for mee too, and with this is not necessary to iter in all table rows. Quite a strange method I would say.Byssus
P
41

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);
}
Pottage answered 3/6, 2011 at 20:39 Comment(7)
-1, Actually, this code doesn't work. First you remove row 0, then all the rows shift down 1. Then you delete row 1, which means row 0 is still there. James_Bond's answer shows how this is done by deleting from the end not the start.Petra
Yes, you're right, the array elements have to be removed from back to front.Pottage
no need for looping - DefaultTableModel has api to clear all rows with a single method call ...Anus
Wondering how this code can work with the i++. Should probably be i--Lylalyle
It doesn't work, it will only delete half of the table, and throw an exception after that. You could replace i inside the loop with 0.Dacoit
Check the updated version. The idea is to remove rows from the end of the table.Pottage
((DefaultTableModel) jtMyTable.getModel()).setRowCount(0)Contentious
N
22

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); 
}
Neon answered 3/6, 2011 at 20:44 Comment(3)
Assuming a typical array-like backing, this is far better than removing the elements front to back.Arronarrondissement
btw: it should be DefaultTableModel, TableModel has no method removeRowStarobin
no need for looping, simply use the api that is meant for clearing the data (not too obvious, but then you probably read @Petra 's answer - which mentions the deprecated method)Anus
L
14

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

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

Lowenstern answered 21/1, 2014 at 15:45 Comment(1)
correct, but nothing new: there is already an earlier answer pointing to that exact method :-) Plus more than one pointing to the older api ..Anus
P
9

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.

Petra answered 4/6, 2011 at 1:40 Comment(0)
M
9

The simplest way to remove all rows from JTable, just use this method instead...

tablemodel.getDataVector().removeAllElements();
tablemodel.fireTableDataChanged();

tablemodel is the model which you created for your table to add new rows. This is the shortest and fastest way of deleting all rows because what if you have thousands of rows? Looping?

Mambo answered 23/11, 2012 at 23:5 Comment(3)
might appear simple - but is wrong: a) the general rule is to never-ever call any fireXX from outside of the model, notifying its listeners is the exclusive responsibility of the model itself. b) DefaultTableModel has api to clear remove all rows (though its name is unfortunate), there's absolutely no need to interact with the underlying data structureAnus
@Anus could you please explain the rule you are talking about? i dont understand why i can't use any fireXX method when they are public and accessible by default implementation!Cyanocobalamin
it's a design accident that they are public - plain OO sanity requires that a) the class does its job completely and b) outsiders never-ever take over the job someone else is responsible forAnus
T
6
try{

    DefaultTableModel dtm = (DefaultTableModel) jTable2.getModel();

    dtm.setNumRows(0); 

}catch(Exception e){
}
Tutuila answered 25/6, 2013 at 11:37 Comment(0)
N
1

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.

Naman answered 3/6, 2011 at 20:52 Comment(1)
while possible, would not recommended (especially, as it's not needed, the DTM has api to remove all its rows) - the implication is that listeners to the old model must be re-wired to the new model. Not rocket science, though, just unnecessary complexity ;-)Anus
B
0

This worked for me, just use

tableModel.setRowCount(0); or tableModel.setNumRows(0);

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. Params: rowCount – number of rows in the model

By setting the number of rows to zero you're are telling the table moble to have no rows, which makes the table empty.

Benzoate answered 27/12, 2021 at 20:31 Comment(0)
B
-1

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();
 }
Bearish answered 20/4, 2013 at 10:41 Comment(1)
-1 sigh - yet another variant of an incorrect answer ... NO there is no need at all to loop and NO there is even less a need to revalidate anything in that loopAnus
U
-1
DefaultTableModel tm = (DefaultTableModel) tbl.getModel();
while(tbl.getRowCount() > 0)
{
    ((DefaultTableModel) tbl.getModel()).removeRow(0);
}
Uticas answered 26/11, 2013 at 11:18 Comment(1)
While this code may help answer the question, code only answers are not high quality. A better answer would explain what the code does, tell where to insert it, explain why this approach was taken, and link to relevant documentation.Oria
E
-1

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);
    }
}
Electrochemistry answered 5/6, 2014 at 8:8 Comment(0)
M
-1
MyModel myTableModel = (MyModel) myTable.getModel();
for (int i = myTableModel.getRowCount()-1; i >= 0; i--) myTableModel.deleteRow(i);
Monti answered 30/12, 2014 at 21:40 Comment(0)
J
-1

You can not simple use for loops here because in every loop you remove a row which decreases the row count. Here's the right one:

int count = tmodel.getRowCount();
    while(count > 0) {
        tmodel.removeRow(count-1);
        count = tmodel.getRowCount();
    }
Jared answered 30/11, 2021 at 7:52 Comment(0)
S
-2
    DefaultTableModel tb = (DefaultTableModel) jTable1.getModel();
    if (jTable1.getSelectedRow() == 0) {
    } else {
        jTable1.selectAll();
        int t = jTable1.getSelectedRow();
        while (t >= 0) {
            tb.removeRow(t);
        }
    }
Sufficiency answered 19/7, 2022 at 23:12 Comment(1)
Please read How do I write a good answer?. While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. - From ReviewRuberta

© 2022 - 2024 — McMap. All rights reserved.