Question

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?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top