![]() |
The Java Developers Almanac 1.4 |
|
e922. Removing a Column from a JTable ComponentTo remove a column to aJTable component, the component must use
a table model that supports this operation. A simple implementation
of such a table model is DefaultTableModel.
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<data.size(); 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;
}
}
e916. Enumerating the Columns in a JTable Component e917. Setting the Width of a Column in a JTable Component e918. Setting the Column Resize Mode of a JTable Component e919. Locking the Width of a Column in a JTable Component e920. Appending a Column to a JTable Component e921. Inserting a Column in a JTable Component e923. Moving a Column in a JTable Component e924. Allowing the User to Move a Column in a JTable Component e925. Allowing the User to Resize a Column in a JTable Component
© 2002 Addison-Wesley. |