Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TableView exclude bottom row (total) from sorting

I have a simple TableView (Java FX 2.0, but I suppose the problem is fairly generic) that gets the default sorting feature. However the table has a total in its last line so I would like to exclude that last line from the sorting algorithm.

I found a solution for a Swing JTable that consists in creating a separate table for the total row - that would be transposable to a TableView but it seems a bit cumbersome. I have tried implementing my own Comparator but I don't think it is possible to create one that would work in both ascending & descending orders.

like image 334
assylias Avatar asked Jan 17 '23 05:01

assylias


1 Answers

With JavaFX 8 it is possible to define a sorting policy, and the problem is easier to fix. Assuming the row containing the totals is TOTAL:

table.sortPolicyProperty().set(t -> {
    Comparator<Row> comparator = (r1, r2) -> 
         r1 == TOTAL ? 1 //TOTAL at the bottom
       : r2 == TOTAL ? -1 //TOTAL at the bottom
       : t.getComparator() == null ? 0 //no column sorted: don't change order
       : t.getComparator().compare(r1, r2); //columns are sorted: sort accordingly
    FXCollections.sort(t.getItems(), comparator);
    return true;
});
like image 122
assylias Avatar answered Jan 28 '23 11:01

assylias