Selected Row in JTable along with Sorting
Asked Answered
C

3

7

I have a very odd issue with JTable.

I put data in JTable from DB. 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. 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.

Any ideas?

Cameraman answered 4/6, 2015 at 13:5 Comment(1)
Could you post your code please? What have you tried so far? how are you doing this?Mitchell
G
11

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.

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.

Let's say that you have the following 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:

table.getRowSorter().convertRowIndexToModel(0); // index 0 here
Garold answered 4/6, 2015 at 13:32 Comment(0)
V
3

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.

Vorticella answered 4/6, 2015 at 13:31 Comment(0)
R
1

Try Sorting your JTable TableModel data too. Jtable -> TableModel is the one which hold the actual data. JTable is just a view.

Roxie answered 4/6, 2015 at 13:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.