javasortingjavafxtableviewjavafx-8

JavaFx - TableView: How to use custom Comparator<T> for sorting?


... where T is the generic type of the TableView.

I'm implementing a file-listview with three columns, so far. Each of type java.nio.file.Path. For the name column, I wrote a Comparator<Path> which sorts the files with directories-first and case-insensitiv. The other two comparators sort by last-modified-time and file-size. For this they compare on long fields.

But the comparatorProperty of a column is based on Comparator<String>. Which, I think, sorts based on the displayed text...

So I have to find a way, to use the sort-on-header-click feature with the type of the TableView?


Solution

  • You use wrong type parameters, when creating your TableColumn. If you create a TableColumn<Path, Path>, you can specify a Comparator<Path> for that column. Likewise TableColumn<Path, FileTime> and TableColumn<Path, Long> to use Comparator<FileTime> and Comparator<Long>.

    From the docs:

    Class TableColumnBase<S,T>
    Type Parameters:
    S - The type of the UI control (e.g. the type of the 'row').
    T - The type of the content in all cells in this table column.