【问题标题】:JavaFX filtering listview using multiple choiceboxesJavaFX 使用多个选择框过滤列表视图
【发布时间】:2019-10-07 17:01:11
【问题描述】:

我目前正在尝试使用通过场景生成器创建的多个选择框来过滤我的 FXML 列表视图。

好吧,在第一次我尝试使用文本字段而不是使用选择框将过滤器功能实现到我的工作中,只是为了测试它是否适用于我的自定义列表视图并且它有效。

但现在我无法弄清楚如何使用多个选择框而不是仅使用文本字段来实现它。

希望这里的人能给我一些关于如何做到这一点的见解,谢谢。

这些是我的选择框

@FXML
private ChoiceBox choiceBox1;
@FXML
private ChoiceBox choiceBox2;
@FXML
private ChoiceBox choiceBox3;
@FXML
private ChoiceBox choiceBox4;

这是我实现过滤器的地方

@Override
    public void initialize(URL location, ResourceBundle resources) {
        filterField.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredData.setPredicate(student -> {
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }
                String lowerCaseFilter = newValue.toLowerCase();
                if (student.getName().toLowerCase().contains(lowerCaseFilter)) {
                    return true;
                } else if (student.getStatus().toLowerCase().contains(lowerCaseFilter)) {
                    return true;
                }
                return false;
            });
        });
        listView.setItems(filteredData);
        listView.setCellFactory(studentListView -> new StudentListViewCell());
}

【问题讨论】:

    标签: java listview javafx filter fxml


    【解决方案1】:

    简单地说,您可以将列表的谓词属性与任何ChoiceBox 的值更改时生成的新谓词值绑定:

    filteredData.predicateProperty().bind(Bindings.createObjectBinding(() -> (Predicate<Student>) student -> {
        // comparisons go here...
        String studentName = student.getName().toLowerCase();
        return choiceBox1.getValue().contains(studentName) || choiceBox2.getValue() == student.getStatus();
    }, choiceBox1.valueProperty(), choiceBox2.valueProperty(), choiceBox3.valueProperty(), choiceBox4.valueProperty()));
    

    【讨论】:

    • 您好,感谢您的回复,很抱歉我忘记提及我对 JavaFX 很陌生,我不明白您在说什么,您能更详细地解释一下吗?感谢和抱歉给您带来的麻烦。
    • 这样,FilteredList 的谓词将在每次 ChoiceBox 的值更改时更新。假设您有一个ChoiceBox,其中包含学生可能拥有的所有可能状态,当用户更改状态选择时,列表的谓词将自动更改,并在此基础上再次过滤数据并您的视图将反映过滤后的项目。最好能解释一下ChoiceBoxes 代表什么。
    • 所以一个学生有一个名字,在读或毕业的状态,他们是第一年,第二年还是第三年,最后他们的专业是工程,科学和商业。每个选择框代表每个元素,我想根据这 4 个元素过滤列表。例如,如果我选择名称 Alex、已注册状态、第二年和商科专业,它应该只显示具有这些元素的学生。
    • 我写的代码完全符合你的要求。例如,定义一个包含 ENROLLED 和 GRADUATED 的 Status 枚举,并将 checkBox2 定义为 ChoiceBox&lt;Status&gt;。这样,代码就可以正常工作,每当用户从该选项框中选择另一个状态时,视图就会自动更新。
    • @CngY 他们已经向您展示了如何实现它。你得到的语法错误是什么?注意这里使用的方法签名是createObjectBinding(Callable,Observable...)
    猜你喜欢
    • 2019-10-08
    • 2012-08-20
    • 1970-01-01
    • 2017-10-28
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多