简体   繁体   中英

Set column indexes after moving a column in JTable

I'm using a JTable , and I need to allow moving of its columns. But there comes the problem. Once they have rearranged, it's like just they have changed there content and title only. But I also need their indexes to be changed as well.

To make this more clear, I'll give an example. Let's say my first column is called "names". When calling the 'setName()' method, a name must always go to that column, no matter where the column is. But not to the first column..Hope you got my point!

I've finished writing required methods. Hope there is a way to achieve this without touching the finished methods.

Any help is much appreciated!!!

To make this more clear, I'll give an example. Let's say my first column is called "names". When calling the 'setName()' method, a name must always go to that column, no matter where the column is. But not to the first column..Hope you got my point!

If you want to change the data, simply alter the underlying TableModel directly. The order of the columns never changes in the TableModel , it is only in the view (the JTable ) that those columns are re-ordered.

If you do want to go through the table, you will have to convert from 'view-coordinates' to 'model-coordinates' by using the available JTable#convertColumnIndexToModel (view -> model) and the JTable#convertColumnIndexToView (model->view) methods as @MadProgrammer mentioned.

You should certainly not update the setValueAt method of the TableModel as you mentioned in one of your comments. As said before, the TableModel does not change the order of the columns, so the setValueAt should always be called with 'model coordinates', hence there is no need to transform those

Oh yeah, I love this, it always gets me ;)

Check out JTable.convertColumnIndexToModel(int viewColumnIndex) and JTable.convertColumnIndexToView(int modelColumnIndex)

Essentially, you need convert the column index to and from the view index.

You shouldn't need to worry about this with the TableModel as it's taken care for you my the JTable .

You'll have a similar issue with the RowSorter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM