How to clear contents of a jTable ?

前端 未结 8 2251
梦如初夏
梦如初夏 2020-12-05 05:41

I have a jTable and it\'s got a table model defined like this:

javax.swing.table.TableModel dataModel = 
     new javax.swing.table.DefaultTableModel(data, c         


        
相关标签:
8条回答
  • 2020-12-05 05:52

    You have a couple of options:

    1. Create a new DefaultTableModel(), but remember to re-attach any listeners.
    2. Iterate over the model.removeRow(index) to remove.
    3. Define your own model that wraps a List/Set and expose the clear method.
    0 讨论(0)
  • 2020-12-05 05:54
    public void deleteAllRows() {
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        model.setRowCount(0);
    }
    
    0 讨论(0)
  • 2020-12-05 06:00

    Another easy answer:

    defaultTableModel.getDataVector().removeAllElements();
    
    0 讨论(0)
  • 2020-12-05 06:04

    I think you meant that you want to clear all the cells in the jTable and make it just like a new blank jTable. For an example, if your table contains 40 raws, you can do following.

    DefaultTableModel model = (DefaultTableModel)this.jTable.getModel();
    model.setRowCount(0);
    model.setRowCount(40);
    
    0 讨论(0)
  • 2020-12-05 06:04

    One of the trivial methods is to use the following option.

    dataModel.setRowCount(0);
    

    dataModel is the model which you would like clear the content on

    However, it is not optiomal solution.

    0 讨论(0)
  • 2020-12-05 06:07

    Easiest way:

    //private TableModel dataModel;
    private DefaultTableModel dataModel;
    
    
    void setModel() {
      Vector data = makeData();
      Vector columns = makeColumns();
      dataModel = new DefaultTableModel(data, columns);
      table.setModel(dataModel);
    }
    
    void reset() {
      dataModel.setRowCount(0);
    }
    

    i.e. your reset method tell the model to have 0 rows of data The model will fire the appropriate data change events to the table which will rebuild itself.

    0 讨论(0)
提交回复
热议问题