How to clear contents of a jTable ?
You have a couple of options:
- Create a
new DefaultTableModel()
, but remember to re-attach any listeners. - Iterate over the
model.removeRow(index)
to remove. - Define your own model that wraps a List/Set and expose the
clear
method.
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);
}
}
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.
//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);
}
}