Javafx: Re-sorting a column in a TableView

betaman picture betaman · Jun 19, 2012 · Viewed 26.7k times · Source

I have a TableView associated to a TreeView. Each time a node in the TreeView is selected, the TableView is refreshed with different data.

I am able to sort any column in the TableView, just pressing the corresponding column header. That works fine.

But: when I select a different node in the tree-view, eventhough the column headers keep showing as sorted. The data is not.

Is there a way to programmatically enforce the sort order made by the user each time the data changes?

Answer

betaman picture betaman · Jun 20, 2012

Ok, I found how to do it. I will summarize it here in case it is useful to others:

Before you update the contents of the TableView, you must save the sortcolum (if any) and the sortType:

        TableView rooms;
        ...
        TableColumn sortcolumn = null;
        SortType st = null;
        if (rooms.getSortOrder().size()>0) {
            sortcolumn = (TableColumn) rooms.getSortOrder().get(0);
            st = sortcolumn.getSortType();
        }

Then, after you are done updating the data in the TableView, you must restore the lost sort-column state and perform a sort.

       if (sortcolumn!=null) {
            rooms.getSortOrder().add(sortcolumn);
            sortcolumn.setSortType(st);
            sortcolumn.setSortable(true); // This performs a sort
        }

I do not take into account the possibility of having multiple columns in the sort, but this would be very simple to do with this information.