TreeTableView and sorting

I have a TreeTableView in my application that I use as a comment panel. Users can create new thread, reply to each other etc. These comments are coming from a server and I need to refresh that panel quite often. I recently discovered that a sorted column before a refresh, was not sorted after. Let’s understand the issue, and resolve it.


First, we need to understand the behavior. It actually comes directly from this bug. When the root of a TreeTableView is changed, the sort order is cleared (internally) :

getSortOrder().clear();

Therefore we understand why the column was not sorted anymore and why a simple call to the “sort()” method was not working.

To get around this issue, we only need to save the sort, and re-apply it when we have refreshed the TreeTableView. In my case, I am retaining only one column :

        //We retain the previous sort applied if any.
        TreeTableColumn sortColumn = null;
        SortType sortType = null;
        if (getSortOrder().size() > 0) {
            sortColumn = getSortOrder().get(0);
            sortType = sortColumn.getSortType();
        }
//Set a new root here

//Then, we re-apply the sort if necessary.
        if (sortColumn != null) {
            getSortOrder().add(sortColumn);
            sortColumn.setSortType(sortType);
            sortColumn.setSortable(true); // This performs a sort
        }

With this simple solution, your TreeTableView will always be sorted the way the user wants it to be.

Leave a Reply

Your email address will not be published. Required fields are marked *