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?

kleopatra
  • 51,061
  • 28
  • 99
  • 211
user489041
  • 27,916
  • 55
  • 135
  • 204
  • @MByD I just added revalidate(), but still seeing the same thing. I am using a CustomeTableCellRenderer, but wouldnt think that would do too much. – user489041 Jun 03 '11 at 20:36
  • I tried this as well. No luck. I think there is something else going on. – user489041 Jun 03 '11 at 20:43
  • 1
    @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. – camickr Jun 04 '11 at 01:42
  • @camickr - that for the information :) – MByD Jun 04 '11 at 01:44
  • voting to close as not-a-real-question - it's not answerable as posted, and evokes one incorrect pseudo-answer after another ... – kleopatra Nov 24 '12 at 11:20
  • check if [this][1] this solves your problem [1]: http://stackoverflow.com/a/25020658/2553431 – Iamat8 Jul 29 '14 at 16:53

15 Answers15

92

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.

Felype
  • 3,087
  • 2
  • 25
  • 36
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);
}
Mihai
  • 600
  • 7
  • 16
  • 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. – camickr Jun 04 '11 at 01:42
  • 2
    Yes, you're right, the array elements have to be removed from back to front. – Mihai Jun 04 '11 at 06:22
  • 1
    no need for looping - DefaultTableModel _has_ api to clear all rows with a single method call ... – kleopatra Sep 25 '12 at 16:48
  • 1
    Wondering how this code can work with the `i++`. Should probably be `i--` – Robin Sep 26 '12 at 05:51
  • 2
    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`. – AdelaN Aug 30 '14 at 18:00
  • Check the updated version. The idea is to remove rows from the end of the table. – Mihai Aug 31 '14 at 12:45
  • 1
    `((DefaultTableModel) jtMyTable.getModel()).setRowCount(0)` – 1ac0 Aug 31 '14 at 12:50
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); 
}
james_bond
  • 6,778
  • 3
  • 28
  • 34
  • 1
    Assuming a typical array-like backing, this is far better than removing the elements front to back. – Dilum Ranatunga Jun 03 '11 at 21:05
  • btw: it should be DefaultTableModel, TableModel has no method removeRow – AvrDragon Sep 25 '12 at 07:34
  • 1
    no need for looping, simply use the api that is meant for clearing the data (not too obvious, but then you probably read @camickr 's answer - which mentions the deprecated method) – kleopatra Sep 25 '12 at 16:47
14

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

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

Chris
  • 161
  • 1
  • 5
  • 1
    correct, but nothing new: there is already [an earlier answer](http://stackoverflow.com/a/15636607/203657) pointing to that exact method :-) Plus more than one pointing to the older api .. – kleopatra Jan 21 '14 at 15:50
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?

GraphicsMuncher
  • 4,583
  • 4
  • 35
  • 50
  • 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 structure – kleopatra Nov 24 '12 at 11:10
  • @kleopatra 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! – Hazhir Aug 27 '13 at 16:21
  • 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 for – kleopatra Aug 28 '13 at 06:45
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.

camickr
  • 321,443
  • 19
  • 166
  • 288
6
try{

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

    dtm.setNumRows(0); 

}catch(Exception e){
}
Tiago Sippert
  • 1,324
  • 7
  • 24
  • 33
codex98
  • 61
  • 1
  • 1
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.

Andrew
  • 617
  • 2
  • 6
  • 19
  • 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 ;-) – kleopatra Nov 24 '12 at 11:16
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.

-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();
 }
Anil
  • 7
  • 2
  • -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 loop – kleopatra Apr 20 '13 at 12:37
-1
DefaultTableModel tm = (DefaultTableModel) tbl.getModel();
while(tbl.getRowCount() > 0)
{
    ((DefaultTableModel) tbl.getModel()).removeRow(0);
}
MrLore
  • 3,759
  • 2
  • 28
  • 36
SwR
  • 612
  • 1
  • 8
  • 21
  • 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. – Stephen Ostermiller Jun 23 '14 at 02:13
-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);
    }
}
nicc777
  • 75
  • 1
  • 3
-1
MyModel myTableModel = (MyModel) myTable.getModel();
for (int i = myTableModel.getRowCount()-1; i >= 0; i--) myTableModel.deleteRow(i);
-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();
    }
-2
    DefaultTableModel tb = (DefaultTableModel) jTable1.getModel();
    if (jTable1.getSelectedRow() == 0) {
    } else {
        jTable1.selectAll();
        int t = jTable1.getSelectedRow();
        while (t >= 0) {
            tb.removeRow(t);
        }
    }
  • 2
    Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-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 Review](https://stackoverflow.com/review/low-quality-posts/32238228) – Saeed Zhiany Jul 20 '22 at 05:08