javafx TableView: Why does the sortOrder listener does not fire when I sort descending?

1.5k Views Asked by At

I have a javafx TableView and I want to know when the sort order of a column changes. I added a listener to the getSortOrder method. However, it only fires when I sort ascending, and never when I sort descending. To test this I used this example code Does anyone have an idea why this doesn't fire? Do I need to add sth else?

The data in the table is in a SortedList and I added the listener as follows:

personTable.getSortOrder().addListener(this::onColumnSortOrderChanged);

 private void onColumnSortOrderChanged(ListChangeListener.Change<? extends TableColumn<Person, ?>> change) {
    boolean changed = false;
    while (change.next()) {
        changed = true;
    }
    if (changed) {
        if (change.getList().isEmpty()) {
            System.out.println("observable is empty");
        } else {
            TableColumn<Person, ?> column = change.getList().get(0);
            System.out.println("Sorted: " + column.getText() + " sort type " + column.getSortType());
        }
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

Multiple columns can be used for sorting (e.g. sorting people by family name first and use given name as secondary criterion). You can hold Shift to add multiple columns. This list does not change, if you're changing between ascending and descending sort order of a column.

To listen to those changes too, you need to listen to the TableColumn.sortType property.

// print sort order on change
table.getSortOrder().addListener((Observable o) -> {
    System.out.println("sort order: "+ table.getSortOrder().stream().map(TableColumn::getText).collect(Collectors.joining(", ", "{", "}")));
});

// print sortType on change
column.sortTypeProperty().addListener(o -> System.out.println("sortType changed to: " + column.getSortType()));