To demonstrate the problem I've got a JTable with a simple DefaultTableModel, and I'm trying to insert new columns on the left hand side of the table. Although the first insertion appears to work, the second insertion seems to undo the first one.
The method I'm using to 'insert' a column is actually to use the DefaultTableModel.addColumn() method to add the column to the end of the table, then use TableColumnModel.moveColumn() to move the column to the start of the table. This avoids actually moving any data in my data structure (which doesn't actually exist in this example).
The table initially has columns labelled 'A B C D'.
Pressing the 'Ins col' button adds a new column labelled '4' and moves it, resulting in '4 A B C D'
But then pressing 'Ins col' again inserts new column 5 at the start of the table, but 4 moves back to the end: '5 A B C D 4'. I was expecting '5 4 A B C D'.
Can anyone see where I'm going wrong? Code below (and apologies, it's from a NetBeans project):
Ben Ernstberger wrote:I think the column moving is only temporary but I don't know why. To solve the problem I would write a TableModel that extends AbstractTableModel instead of DefaultTableModel. That is more expensive but you have more control about your table and you can easy move columns.
The TableModel in my 'real' code does extend AbstractTableModel, and I'm trying to solve this problem to improve efficiency ie. by moving columns on the display without moving it in my data structures. (When I write the data back to file after the user has finished editing it I write it in the displayed column order rather than data structure column order.)
So I would really like to understand what's going on - I'd like to think it's a bug in Swing, but somehow I think that's unlikely
You can prevent this from happening by using code like:
So now the initial TableColumns for the table are created when the model is set for the table but no further TableColumns will be created for the table when the structure of the TableModel changes.
But, you now need to manually add a TableColumn to the TableColumnModel of the JTable: