java 当用户对 JTable 进行排序时,如何跟踪行索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4151850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:03:00  来源:igfitidea点击:

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

javaswingjtable

提问by nits.kk

I have a JTable which 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.

我有一个第一行空白的 JTable。现在,当我通过单击该列对表格进行排序时,空白行位于底部。如果我在空白行中插入一些内容并进行排序,则相应地放置该行。即使已排序,我如何跟踪其行索引。我需要访问该行,但如果用户进行排序,那么我会丢失行索引,因为它不再是第一行。

回答by heavi5ide

Assuming you're using the TableRowSorterstuff added in Java 6, I think what you need to look at are the methods convertRowIndexToModeland convertRowIndexToViewin the RowSorterClass. You'd do something like

您所使用的假设TableRowSorterJava 6中新增的东西,我认为你需要什么,在看的方法convertRowIndexToModel,并convertRowIndexToViewRowSorter类。你会做类似的事情

table.getRowSorter().convertRowIndexToView(0)

table.getRowSorter().convertRowIndexToView(0)

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

从您的模型中找出哪个可见行索引实际上是行索引 0。

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)

编辑:正如 Tulskiy 在评论中指出的那样,如果没有为表分配行排序器,这可能会导致 NullPointerException。最好直接在 JTable 上使用这些方法,例如table.convertRowIndexToView(0)

回答by Denis Tulskiy

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.

JTable.convertRowIndexToView()将根据其在模型中的索引返回视图中该行的索引。JTable.convertRowIndexToModel()会做相反的事情。

回答by Roshan Gerard Bolonna

SOLUTION 1

解决方案 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).

jTable1.convertRowIndexToModel(jTable1.getSelectedRow())如果根据日期或时间对值进行排序,则使用时会出现一些问题,convertRowIndexToView(0)因此使用会返回不正确的值convertRowIndexToModel(0)

SOLUTION 2

解决方案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);