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

时间:2016-01-19 23:49:47

标签: java javafx

我希望默认情况下对TableView的某个列进行排序。我该怎么做?我尝试了column.setSortType(SortType.ASCENDING);,并将其置于runLater电话中。我查看了JavaDocs和东西,我所能看到的可能是特有的setSortPolicy方法。

2 个答案:

答案 0 :(得分:7)

执行"一次性"排序,打电话

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

传入您希望数据排序的TableColumn

要使排序保持不变,即使列表中的项目发生更改,也请创建SortedList并将其传递给表格的setItems(...)方法。 (要更改项目,您仍将操纵基础列表。)

例如,您可以使用通常的contact table example

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

答案 1 :(得分:0)

在表格初始化时调用...

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