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?
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
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 is the one which hold the actual data. JTable is just a view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With