Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selected Row in JTable along with Sorting

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?

like image 467
Bharat Nanwani Avatar asked Jun 04 '15 13:06

Bharat Nanwani


3 Answers

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
like image 53
cнŝdk Avatar answered Oct 09 '22 00:10

cнŝdk


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.

like image 26
trashgod Avatar answered Oct 08 '22 23:10

trashgod


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

like image 24
Naren Pamsa Avatar answered Oct 09 '22 01:10

Naren Pamsa