Deleting all the rows in a JTable

前端 未结 12 645
生来不讨喜
生来不讨喜 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:09

    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?

    0 讨论(0)
  • 2020-12-09 03:10
    try{
    
        DefaultTableModel dtm = (DefaultTableModel) jTable2.getModel();
    
        dtm.setNumRows(0); 
    
    }catch(Exception e){
    }
    
    0 讨论(0)
  • 2020-12-09 03:11

    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); 
    }
    
    0 讨论(0)
  • 2020-12-09 03:13
    MyModel myTableModel = (MyModel) myTable.getModel();
    for (int i = myTableModel.getRowCount()-1; i >= 0; i--) myTableModel.deleteRow(i);
    
    0 讨论(0)
  • 2020-12-09 03:17
    DefaultTableModel tm = (DefaultTableModel) tbl.getModel();
    while(tbl.getRowCount() > 0)
    {
        ((DefaultTableModel) tbl.getModel()).removeRow(0);
    }
    
    0 讨论(0)
  • 2020-12-09 03:18

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