开发者

How to Keep Track of row index when JTable has been sorted by the user?

开发者 https://www.devze.com 2023-01-24 06:49 出处:网络
I have a JTable whi开发者_运维知识库ch has 1st row blank. Now when I sort the table based on a column by clicking on that column then the blank row goes at the bottom. If I insert something in the bla

I have a JTable whi开发者_运维知识库ch has 1st row blank. Now when I sort the table based on a column by clicking on that column then the blank row goes at the bottom. If I insert something in the blank row and do the sorting then the row is placed accordingly. How do I keep track of its row index even when it is sorted. I need to access that row but if user does the sorting then i loose the row index as it is no more the 1st row.


Assuming you're using the TableRowSorter stuff added in Java 6, I think what you need to look at are the methods convertRowIndexToModel and convertRowIndexToView in the RowSorter Class. You'd do something like

table.getRowSorter().convertRowIndexToView(0)

to find out which visible row index is actually row index 0 from your model.

Edit: As Tulskiy pointed out in the comments, this may cause a NullPointerException if no row sorter is assigned to the table. Better to use the methods directly on JTable instead, e.g. table.convertRowIndexToView(0)


JTable.convertRowIndexToView() will return you an index of the row in the view based on its index in the model. JTable.convertRowIndexToModel() will do the opposite.


SOLUTION 1

There is some issue when using jTable1.convertRowIndexToModel(jTable1.getSelectedRow()) if you sort the values according to date or time will return incorrect values from the convertRowIndexToView(0) therefore use convertRowIndexToModel(0).

SOLUTION 2

This will retrieve from the new model when sorted.

jTable1.getValueAt(jTable1.getSelectedRow(), 0);

This will retrieve value according to the original index even when sorted.

((DefaultTableModel)jTable1.getModel()).getValuAt(jTable1.getSelectedRow(), 0);
0

精彩评论

暂无评论...
验证码 换一张
取 消