Java 8 SortedList TableView没有刷新

时间:2014-01-16 20:15:54

标签: java javafx javafx-8 java-8 sortedlist

我正在使用TableView来可视化由ObservableList备份的SortedList。

SortedList的比较器绑定到TableView的比较器:

sortedList().comparatorProperty().bind(tableView.comparatorProperty());

当我将一个项添加到基础ObservableList时,SortedList按预期排序(通过所选TableView的比较器)。

虽然当我更改ObservableList的属性(使用CheckBoxTableCell,但这不重要)时,SortedList不会再次排序。

这应该有用还是我必须找到解决方法?

我正在使用jdk 8 b121。

1 个答案:

答案 0 :(得分:2)

注意:这个答案假定"更改了ObservableList的属性"实际应该阅读"更改ObservableList"的项目的属性。假设不正确,我会删除。

SortedList是用于TableView中可排序数据的 干净解决方案 - 它的设计和实现是为了在更改包装列表时保持自身排序。前提是,支持列表向其侦听器通知有关更改的信息。这可以在不需要额外的客户端代码来修改列表的情况下工作(例如添加/删除/设置项目)。

另一方面,它没有一般的方法可以知道包含项的属性的修改:客户端代码必须提供一个提取器(也就是返回一个Observables数组的回调),它允许列表触发更新事件到它的听众。

一个例子(Person是一个具有明显属性的演示bean - 用你最喜欢的示例bean替换),编辑按钮只是预先设置了一个" z"到所选人员的姓氏。

public class TableViewSortSample extends Application {

    private Parent getContent() {
        // wrap the backing list into an observableList with an extractor
        ObservableList<Person> persons = FXCollections.observableList(
                Person.persons(),
                person -> new Observable[] {person.lastNameProperty(), person.firstNameProperty()}            
        );
        // wrap the observableList into a sortedList
        SortedList<Person> sortedPersons = new SortedList<>(persons);
        // set the sorted list as items to a tableView
        TableView<Person> table = new TableView<>(sortedPersons);
        // bind the comparator of the sorted list to the table's comparator
        sortedPersons.comparatorProperty().bind(table.comparatorProperty());
        TableColumn<Person, String> firstName = new TableColumn<>("First Name");
        firstName.setCellValueFactory(new PropertyValueFactory<>("firstName"));
        TableColumn<Person, String> lastName = new TableColumn<>("Last Name");
        lastName.setCellValueFactory(new PropertyValueFactory<>("lastName"));
        table.getColumns().addAll(firstName, lastName);
        Button edit = new Button("Edit");
        edit.setOnAction(e -> {
            Person person = table.getSelectionModel().getSelectedItem();
            if (person != null) {
                person.setLastName("z" + person.getLastName());
            }
        });
        VBox pane = new VBox(table, edit);
        return pane;
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setScene(new Scene(getContent()));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}