I have no ideas what to do. I am creating an application. I need to work with the table, so I am using JTable. But I have a lot problems with it.
It seems to work, but when I try to delete column it this column disappears (only in GUI), but all the information still exists. Also columncount doesn't change.
I have searched and tried a lot of different code, but nothing changed.
public void addTblCol(JTable table,String name) {
DefaultTableModel model = (DefaultTableModel)table.getModel();
TableColumn col = new TableColumn(model.getColumnCount());
col.setHeaderValue(name);
table.addColumn(col);
model.addColumn(name);
this.realColCnt++;
};
public void delTblCol(JTable table,int index) {
DefaultTableModel model = (DefaultTableModel)table.getModel();
TableColumn col = table.getColumnModel().getColumn(index);
table.removeColumn(col);
table.revalidate();
this.realColCnt--;
};
The DefaultTableModel
supports a setColumnCount()
method which effectively will allow you to remove columns from the end of the model only.
If you want to remove columns from the middle of the model, then you will need to:
DefaultTableModel
and create your own removeColumn(int column)
method. Vector.remove(int)
method to remove the column for ever row. fireTableStructureChanged()
method to tell the table that a column has been removed so the table can be repainted.Some general information related to your question.
The JTable API for public void removeColumn(TableColumn aColumn)
explicitly states:
Removes aColumn from this JTable's array of columns. Note: this method does not remove the column of data from the model; it just removes the TableColumn that was responsible for displaying it.
So the behavior you're experiencing is to be expected. If you're trying to remove data from the model, then you're going to have to change your TableModel's data and ColumnModel. Again for more specific help, you'll need to tell us more.
Consider creating a custom table model and giving it a removeColumn(...)
method that removes all the data from a single column, and then calls the appropriate fireXXX(...)
method.
Edit
You state in comment:
THx for answer , I am newbie . This prog is such for studying I have wasted two day for creating it.And now again have problems with it. What is the easiest way ?
That all depends on what you want to do. If you want to just change the display, then remove the column as you're doing and leave the data alone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With