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.
With Table view, you can sort any column in ascending or descending order by clicking on the column header and selecting a sorting option from the dropdown menu or using the 'Sort by' option in the main toolbar.
To select a row with a specific index you can use the select(int) method. Here is an example of selecting a single row with a given index in a JavaFX TableView: selectionModel. select(1);
Calling refresh() forces the TableView control to recreate and repopulate the cells necessary to populate the visual bounds of the control. In other words, this forces the TableView to update what it is showing to the user.
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(...));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With