In Java, I use DefaultTableModel to dynamically add a column to JTable.
//create DefaultTableModel with columns and no rows DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0); JTable table = new JTable(tableModel);
The variable columnNames is a string array with column names. Thus, after starting the program, the user can add additional columns. I do it as follows
tableModel.addColumn("New column name");
Which dynamically adds a column to the table as desired. The user can also delete the added columns. For this, I use the following code:
TableColumn tcol = table.getColumnModel().getColumn(0); table.getColumnModel().removeColumn(tcol);
which should remove the column at the specified index, I also tried:
table.removeColumn(sheet.getColumn(assessmentName));
Both of them work (visually), but here is the problem. After deleting the added column, if another column is added and the table is updated, the previously deleted column will reappear. Therefore, when it visually deletes a column, none of the last two code fragments actually removes it from the model. I assume that since the column was added to the model, where should it be deleted? Is there a specific method that I need to call or some kind of logic that I need to implement in order to remove the column?
java swing tablemodel
Mark
source share