Reputation: 371
I am having difficulties with deleting the actual data under a particular column which I am trying to delete. I actually want to delete the column and its underlying data. I am able to insert new columns but when I delete and insert again, the old columns which I previously deleted pop up again.
Any sort help is appreciated.
Thank you in advancce.
Upvotes: 0
Views: 632
Reputation: 371
public void removeColumnAndData(JTable table, int vColIndex) { MyTableModel model = (MyTableModel)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<TableColumn> enum1 = table.getColumnModel().getColumns();
for (; enum1.hasMoreElements(); ) {
TableColumn c = (TableColumn)enum1.nextElement();
if (c.getModelIndex() >= columnModelIndex) {
c.setModelIndex(c.getModelIndex()-1);
}
}
model.fireTableStructureChanged();
}
/*MyDefaultTableModel class**/
class MyTableModel extends DefaultTableModel
{
String columns[];
int size;
public MyTableModel(String col[],int size)
{
super(col,size);
columns = col;
this.size=size;
}
public Vector getColumnIdentifiers()
{
return columnIdentifiers;
}
}
Upvotes: 0
Reputation: 347184
The data is stored in the TableModel
.
Deleting the column from the ColumnModel
will only prevent the view (the JTable
) from showing it.
In order to remove it, you need to tell the TableModel
to remove the column data as well.
Depending on you implementation, you could use JTable.setValueAt(value, row, column)
or TableModel.setValueAt(value, row, column)
, which ever is more convenient.
This of course assumes you've implemented the setValueAt
method
Upvotes: 2