tags:

views:

37

answers:

3

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?

+1  A: 

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);
    }
}
eee
Sorry, i want to return the table to a state where its just got the column headers but no data in it
tom
+1  A: 

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
willcodejavaforfood
+2  A: 

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.

locka
+1, (with a slight change), the TableModel interface does not have a setRowCount() method. That method is found in the DefaultTableModel class. I edited your sample code to use the DefaultTableModel, not the TableModel.
camickr
+1 ...right, I forgot about DefaultTableModel.SetRowCount(0)
eee