开发者

How to clear contents of a jTable ?

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, columns);
tblCompounds.setModel(dataModel);

Does anyone know how I can clear its contents ? Just so it returns to an empty table ?


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.


If you mean to remove the content but its cells remain intact, then:

public static void clearTable(final JTable table) {
   for (int i = 0; i < table.getRowCount(); i++) {
      for(int j = 0; j < table.getColumnCount(); j++) {
          table.setValueAt("", i, j);
      }
   }
}

OK, if you mean to remove all the cells but maintain its headers:

public static void deleteAllRows(final DefaultTableModel model) {
    for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
        model.removeRow(i);
    }
}


    //To clear the Contents of Java JTable

    DefaultTableModel dm = (DefaultTableModel) JTable1.getModel();

    for (int i = 0; i < dm.getRowCount(); i++) {
        for (int j = 0; j < dm.getColumnCount(); j++) {
            dm.setValueAt("", i, j);
        }
    }


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.


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


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.


Another easy answer:

defaultTableModel.getDataVector().removeAllElements();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜