Search code examples
javaswingsortingjtablefiltering

JTable Sorting and Filtering


I am creating a program that filters the contents of a JTable using two columns. I have used a RowSorter and everything works fine - at least according to what I can see (the view).

Each row on the table can be double clicked to open a dialog. This dialog allows you to edit information on the table. However, the information on the dialog is still of that of the original view (before filtering was used).

Example:

Before filtering the first row on the table is row a. After filtering the first row on the table is row b.

However, when I double click to open the dialog on the first row (after filtering, which should now be row b, the dialog for row a opens.) [Hope I've explained this well enough]

I think my problem is that the model isn't being updated after the filters have taken place. I've tried:

        for(int i = 0; i < table.getRowCount(); i++){
        table.convertRowIndexToView(i);
    }

and

for(int i = 0; i < table.getRowCount(); i++){
        table.convertRowIndexToModel(i);
    }

I am also getting a similar problem when I sort the table using the column headers.

How do I fix this problem?


Solution

  • I think my problem is that the model isn't being updated after the filters have taken place

    The model is never updated.

    Only the view is updated to show the data from the model in a sorted/filtered order.

    Each row on the table can be double clicked to open a dialog.

    So I assume you copy the data for one row to the dialog so it can be edited and then added back to the original model.

    Therefore you need to use the convertRowIndexToModel(...) to get the model row number so you can access the model data to be displayed on the edit dialog. You would only do this for the row to be edited, not the entire table.