javaswingtablerowsorter

Get user object in the selected row when TableRowSorter is clicked


I am using a table model to handle data in the table. In that,

I use ArrayList<MyUserObject>datalist to hold the data of the model. I'm retriving the user object using the following method in the model:

public MyUserObject getMyUserObject(int rowIndex)
{
    return datalist.get(rowIndex);
}

So when a row of the table is got selected I'm able to get the index of the selected row with ListSelectionListener using dataTable.getSelectedRow() and using that value I'm able to retrieve the user object from model using the above method.

But when TableRowSorter is used I'm unable to get the actual value of the user object in the selected row. Because when tablesorter is clicked the row index of the data is changed. But in the model it remains unchanged. So I'm unable to get the correct user object regarding the selected row.

In other words, row order changes in the table should be reflected in the model.

Should I rearrange the arraylist in the model? Or Are there any other easy ways to do that?

How can I resolve this problem?


Solution

  • I'm able to get the index of the selected row with

    Then you need to convert the index to the model row:

    int modelRow = table.convertRowIndexToModel(selectedRow);