简体   繁体   English

如何以编程方式对TableView进行排序?

[英]How to sort a TableView programmatically?

I want a certain column of a TableView to be sorted by default. 我希望默认情况下对TableView的某个列进行排序。 How would I do this? 我该怎么做? I tried doing column.setSortType(SortType.ASCENDING); 我尝试过做column.setSortType(SortType.ASCENDING); , as well as putting it in a runLater call. ,以及将其置于runLater调用中。 I looked at the JavaDocs and stuff and all I can see that may be of interest is the peculiar setSortPolicy method. 我查看了JavaDocs和其他东西,我所能看到的可能是有趣的是特殊的setSortPolicy方法。

To perform a "one-off" sort, call 要执行“一次性”排序,请致电

tableView.getSortOrder().setAll(...);

passing in the TableColumn (s) by which you want the data sorted. 传递您想要对数据进行排序的TableColumn

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. 要使排序保持不变,即使列表中的项目发生更改,也要创建一个SortedList并将其传递给表的setItems(...)方法。 (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(...));

Called at the end of the table initialisation... 在表初始化时调用...

colChecked.setSortType(TreeTableColumn.SortType.DESCENDING);
colDate.setSortType(TreeTableColumn.SortType.DESCENDING);
treeView.getSortOrder().setAll(colChecked, colDate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM