Reputation: 3012
I want a certain column of a TableView
to be sorted by default. How would I do this? I tried doing column.setSortType(SortType.ASCENDING);
, as well as putting it in a runLater
call. I looked at the JavaDocs and stuff and all I can see that may be of interest is the peculiar setSortPolicy
method.
Upvotes: 6
Views: 10921
Reputation: 12627
Called at the end of the table initialisation...
colChecked.setSortType(TreeTableColumn.SortType.DESCENDING);
colDate.setSortType(TreeTableColumn.SortType.DESCENDING);
treeView.getSortOrder().setAll(colChecked, colDate);
Upvotes: 2
Reputation: 209225
To perform a "one-off" sort, call
tableView.getSortOrder().setAll(...);
passing in the TableColumn
(s) by which you want the data sorted.
To make the sort persist even as the items in the list change, create a SortedList
and pass it to the table's setItems(...)
method. (To change the items, you will still manipulate the underlying list.)
As an example, using the usual contact table example you could do:
TableView<Person> table = new TableView<>();
TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
TableColumn<Person, String> lastNameCol = new TableColumn<>("
Last Name");
firstNameCol.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
ObservableList<Person> data = FXCollections.observableArrayList();
SortedList<Person> sortedData = new SortedList<>(data);
// this ensures the sortedData is sorted according to the sort columns in the table:
sortedData.comparatorProperty().bind(table.comparatorProperty());
table.setItems(sortedData);
// programmatically set a sort column:
table.getSortOrder().addAll(firstNameCol);
// note that you should always manipulate the underlying list, not the sortedList:
data.addAll(new Person(...), new Person(...));
Upvotes: 14