TableView 在过滤之前不显示数据

TableView not showing data until filter

我在 JavaFX 中创建了这个 GUI

问题是,当我尝试 运行 readList 函数时,table 中不会显示任何内容,但是,如果我尝试使用某些东西进行过滤, 数据出现。

我做错了什么? SortedList 是否链接到 Filtered,而 Filtered 链接到正在监视人员列表的 ObservableCollection? 每当我更改该列表中的某些内容时,不应该自动更新 TableView 吗?

那是控制器

public class LetturaAwpController {

    List<Person> persons= new LinkedList<Person>();

    ObservableList<Person> observablePerson = FXCollections.observableList(persons);

    @FXML
    private TextField txtUser;

    @FXML
    private TextField txtPass;

    @FXML
    private TextField txtFiltraId;

    @FXML
    private CheckBox chkMag;

    @FXML
    private TableView<Person> tblMain;

    @FXML
    private TableColumn<Person, String> colId;

    @FXML
    void doRead(ActionEvent event) {

        if(txtPass.getText().isEmpty() | txtUser.getText().length() < 6)
            return;
        if (persons== null)
            persons= model.readList(txtUser.getText(), txtPass.getText());
        else
            persons.addAll(model.readList(txtUser.getText(), txtPass.getText()));
    }

    @FXML
    void initialize() {

        FilteredList<Person> filteredPerson= new FilteredList<>(observablePerson , p-> true);

        colId.setCellValueFactory(new PropertyValueFactory<Person,String>("idApparecchio"));    

        txtFiltraId.textProperty().addListener((observable, oldValue, newValue)-> {
            filteredSlot.setPredicate(person-> {
                if (newValue == null || newValue.isEmpty()){
                    return true;
                }

                String lowerCaseFilter = newValue.toLowerCase();

                if(person.getIdApparecchio().toLowerCase().contains(lowerCaseFilter)){
                    return true;
                } else if (person.getNomeModello().toLowerCase().contains(lowerCaseFilter)){
                    return true;
                }
                return false;
            });
        });

        SortedList<Person> sortedData = new SortedList<>(filteredPerson);

        // 4. Bind the SortedList comparator to the TableView comparator.
        sortedData.comparatorProperty().bind(tblMain.comparatorProperty());

        // 5. Add sorted (and filtered) data to the table.
        tblMain.setItems(sortedData);

    }

}

Isn't the SortedList linked to the Filtered that is linked to the ObservableCollection

对对对(虽然没有ObservableCollection,但是ObservableList

that is watching the persons list?

没有

ObservableList 没有监视传递给 FXCollections.observableList 的列表,它创建了一个由 List 支持的 ObservableList。修改后备列表不会通知添加到 ObservableList 的监听​​器; ObservableList 只是使用后备列表来存储它的元素。 FilteredList 然而,它依赖于一个监听器。

这意味着:不要使用写访问权限访问后备列表。改为修改 ObservableList

observablePerson.addAll(model.readList(txtUser.getText(), txtPass.getText()));

此外,如果您初始化字段并且从不修改它,则 if (persons== null) 检查是不必要的。同样,简单地替换该字段将导致 ObservableList 得到与存储在该字段中的列表不同的列表的支持...