简体   繁体   English

JTable中的选定行以及排序

[英]Selected Row in JTable along with Sorting

I have a very odd issue with JTable. 我对JTable有一个非常奇怪的问题。

I put data in JTable from DB. 我把数据从数据库放到JTable中。 When user double clicks on any cell, it copies the cell contents of the first column of the row where user double clicked. 当用户双击任何单元格时,它会复制用户双击的行的第一列的单元格内容。 So far, it works perfect. 到目前为止,它完美无缺。

The problem arises when the user sorts the JTable by clicking on the header. 当用户通过单击标题对JTable进行排序时,会出现问题。 when the table has been sorted and now when the user double clicks on any row, it doesn't what is currently stored on that row's first column. 当表已经排序时,现在当用户双击任何行时,它不会当前存储在该行的第一列上。 It copies what was originally stored on the first column of that row when the JTable was not sorted. 当JTable未排序时,它会复制最初存储在该行第一列的内容。

Any ideas? 有任何想法吗?

Problem: 问题:

The problem here is that you are getting the initial rows indexes in the JTable TableModel , and not the relevants row indexes shown in the table view. 这里的问题是您在JTable TableModel中获取初始行索引,而不是表视图中显示的相关行索引。

Solution: 解:

You can map the shown indexes of a sorted jTable with their relevants ones in the dataModel using convertRowIndexToModel(index) method which takes in input the row index in the view and returns the index of the corresponding row in the model. 您可以使用convertRowIndexToModel(index)方法将已排序的jTable的显示索引与dataModel中的相关索引映射,该方法在视图中输入行索引并返回模型中相应行的索引。

Let's say that you have the following jTable: 假设你有以下jTable:

TableModel myModel = createMyTableModel();
JTable table = new JTable(myModel);
table.setRowSorter(new TableRowSorter(myModel));

And then loop throught model indexes and use this method with each index to get its corresponding one in the TableModel : 然后循环遍历模型索引并使用此方法与每个索引在TableModel获取其对应的索引:

table.getRowSorter().convertRowIndexToModel(0); // index 0 here

As suggested in How to Use Tables: Sorting and Filtering , "When using a sorter, always remember to translate cell coordinates." 如“ 如何使用表:排序和过滤 ”中所述,“使用分拣机时,请始终记住转换单元格坐标。” Most likely, you have neglected this in your event handler. 最有可能的是,您在事件处理程序中忽略了这一点。

Try Sorting your JTable TableModel data too. 尝试对JTable TableModel数据进行排序。 Jtable -> TableModel is the one which hold the actual data. Jtable - > TableModel是保存实际数据的那个。 JTable is just a view. JTable只是一个视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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