Selected row in JTable along with sorting

I have a very strange problem with JTable.

I have put data into JTable from DB. When the user double-clicks on any cell, it copies the contents of the cell to the first column of the row where the user double-clicked. So far it works fine.

The problem occurs when the user sorts the JTable by clicking on the title. when the table was sorted, and now when the user double-clicks on any row, he does not store the first column in that row. It copies what was originally stored in the first column of that row when the JTable was not sorted.

Any ideas?

+3


source to share


3 answers


Problem:

The problem is that you are getting the indexes of the starting rows in JTable TableModel

, not the indexes of the relevant rows shown in the table view.

Decision:

You can map the shown indices of the sorted jTable to their relevant values ​​in the dataModel using the convertRowIndexToModel (index) method , which takes an input row index in the view and returns the index of the corresponding row in the model.



Let's say you have the following jTable:

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

      

And then loop over the model indices and use this method with each index to get its corresponding in TableModel

:

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

      

+4


source


As stated in How to Use Tables: Sorting and Filtering : "When using a sorter, always remember to translate cell coordinates." Most likely, you ignored this in your event handler.



+2


source


Try to sort your JTable TableModel data as well. Jtable -> TableModel is the one that contains the actual data. JTable is just a view.

+1


source







All Articles