5
votes

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?

3
Could you post your code please? What have you tried so far? how are you doing this? - cнŝdk

3 Answers

8
votes

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
3
votes

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.

1
votes

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