Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Column from TableModel in Java

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?

like image 516
Mark Avatar asked May 09 '11 14:05

Mark


People also ask

How do you delete a column in Java?

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.

How to delete column in JTable?

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.

How do you select a column in Java?

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.


1 Answers

For your table, try calling table.setAutoCreateColumnsFromModel(false);

This post has a good example as to how to delete column and the underlying data.

like image 163
Bala R Avatar answered Oct 05 '22 23:10

Bala R