Deleting all the rows in a JTable

前端 未结 12 646
生来不讨喜
生来不讨喜 2020-12-09 02:38

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()         


        
相关标签:
12条回答
  • 2020-12-09 03:23

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-09 03:27

    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.

    0 讨论(0)
  • 2020-12-09 03:30

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

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

    0 讨论(0)
  • 2020-12-09 03:31

    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.

    0 讨论(0)
  • 2020-12-09 03:32

    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.

    0 讨论(0)
  • 2020-12-09 03:34

    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();
     }
    
    0 讨论(0)
提交回复
热议问题