In Java I'm using the DefaultTableModel to dynamically add a column to a JTable.
//create DefaultTableModel with columns and no rows
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(tableModel);
The columnNames variable is a string array with the column names. So after the program is up and running the user has the option to add additional columns. I do so as follows
tableModel.addColumn("New column name");
Which dynamically adds the column to the table as desired. The user can also remove columns added. For this I use the following code:
TableColumn tcol = table.getColumnModel().getColumn(0);
table.getColumnModel().removeColumn(tcol);
which should remove the column at a specified index, I've also tried:
table.removeColumn(sheet.getColumn(assessmentName));
Both of them work (visually), but here's the problem. After deleting an added column, if another column is added and the table refreshes, the previously deleted column is there again. So while it is removing the column visually, neither of the last two code snippets actually removes it from the model. I'm assuming here that since the column was added to the model that is where it needs to be removed from? Is there a specific method that I need to call or some logic that I need to implement to remove the column?
If you want to remove columns from the middle of the model, then you will need to: extend the DefaultTableModel and create your own removeColumn(int column) method. This method would need to loop through every row in the Vector and use the Vector. remove(int) method to remove the column for ever row.
Removing a column from a JTable means deleting the column containing the data. For removing the column, use the removeColumn() method, for this, you need the index of column that have to be deleted from the JTable.
To select a column in a JTable, use the setColumnSelectionInterval() and set the interval for the column you would like to select. For example, if you want to select a single column i.e. column2, then set the interval as (2,2) in the setColumnSelectionInterval() method.
For your table, try calling table.setAutoCreateColumnsFromModel(false);
This post has a good example as to how to delete column and the underlying data.
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