且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何基于排序的过滤列表在JavaFX中向TableView添加新行?

更新时间:2023-12-06 16:06:40

排序(和过滤)的列表不可修改.您应该修改基础列表(data2),排序/过滤后的列表将自动更新(它会观察基础ObservableList).

Sorted (and filtered) lists are unmodifiable. You should modify the underlying list (data2), and the sorted/filtered list will update automatically (it is observing the underlying ObservableList).

您需要的代码如下:

public class FXMLTableViewController {

    @FXML
    private TableView<Entity> tableView;

    @FXML
    private JFXTextField searchBox;

    @FXML
    public void initialize() throws IOException, ParseException {

        FilteredList<Entity> filteredData = new FilteredList<>   (data2, p -> true);
        searchBox.textProperty().addListener((observable, oldValue,    newValue) -> {
            filteredData.setPredicate(person -> {
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }

                String lowerCaseFilter = newValue.toLowerCase();
                return Person.getPsfName_add().toLowerCase().contains(lowerCaseFilter)
            });
        });
        SortedList<Entity> sortedData = new SortedList<>(filteredData);
        sortedData.comparatorProperty().bind(tableView.comparatorProperty());
        tableView.setItems(sortedData);

        data2.add(new Entity("")); //error line 

    }

}

为清楚起见,请注意,我删除了对tableView.setItems(...)的第一个调用,因为之后您仅将items设置为其他设置.还要注意,tableView.refresh()是多余的(表也在观察组成其项的ObservableList).

Note for clarity I removed the first call to tableView.setItems(...) as you are only setting items to something else immediately afterwards. Also note that tableView.refresh() is redundant (the table is also observing the ObservableList that makes up its items).