Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a TableView programmatically?

Tags:

java

javafx

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.

like image 473
Chris Smith Avatar asked Jan 19 '16 23:01

Chris Smith


People also ask

How to sort a Table view?

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.

How to select a row in TableView JavaFX?

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);

What does TableView refresh do?

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.


1 Answers

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(...));
like image 82
James_D Avatar answered Sep 26 '22 01:09

James_D