Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javafx: Re-sorting a column in a TableView

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?

like image 885
betaman Avatar asked Jun 19 '12 07:06

betaman


2 Answers

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.

like image 148
betaman Avatar answered Sep 30 '22 04:09

betaman


I had the same problem and found out that after an update of the data you only have to call the function sort() on the table view:

TableView rooms;
...
// Update data of rooms
...
rooms.sort()

The table view knows the columns for sorting thus the sort function will sort the new data in the wanted order. This function is only available in Java 8.

like image 41
maddin79 Avatar answered Sep 30 '22 05:09

maddin79