To remove a column to a JTable component, the component must use a table model that supports this operation. A simple implementation of such a table model is DefaultTableModel.
DefaultTableModel.removeColumn() removes the visible column, but leaves the column data in the table model. This example provides a routine that removes both the visible column and the column data.
DefaultTableModel model = new MyDefaultTableModel();
JTable table = new JTable(model);
table.setModel(model);
// Create 3 columns
model.addColumn("Col1");
model.addColumn("Col2");
model.addColumn("Col3");
model.addRow(new Object[]{"v1"});
// Remove the first visible column without removing the underlying data
table.removeColumn(table.getColumnModel().getColumn(0));
// Disable autoCreateColumnsFromModel to prevent
// the reappearance of columns that have been removed but
// whose data is still in the table model
table.setAutoCreateColumnsFromModel(false);
// Remove the first visible column and its data
removeColumnAndData(table, 0);
// Remove the last visible column and its data
removeColumnAndData(table, table.getColumnCount()-1);
// Removes the specified column from the table and the associated
// call data from the table model.
public void removeColumnAndData(JTable table, int vColIndex) {
MyDefaultTableModel model = (MyDefaultTableModel)table.getModel();
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int columnModelIndex = col.getModelIndex();
Vector data = model.getDataVector();
Vector colIds = model.getColumnIdentifiers();
// Remove the column from the table
table.removeColumn(col);
// Remove the column header from the table model
colIds.removeElementAt(columnModelIndex);
// Remove the column data
for (int r=0; r Vector row = (Vector)data.get(r);
row.removeElementAt(columnModelIndex);
}
model.setDataVector(data, colIds);
// Correct the model indices in the TableColumn objects
// by decrementing those indices that follow the deleted column
Enumeration enum = table.getColumnModel().getColumns();
for (; enum.hasMoreElements(); ) {
TableColumn c = (TableColumn)enum.nextElement();
if (c.getModelIndex() >= columnModelIndex) {
c.setModelIndex(c.getModelIndex()-1);
}
}
model.fireTableStructureChanged();
}
// This subclass adds a method to retrieve the columnIdentifiers
// which is needed to implement the removal of
// column data from the table model
class MyDefaultTableModel extends DefaultTableModel {
public Vector getColumnIdentifiers() {
return columnIdentifiers;
}
}