创建搜索TextField字段以在javafx tableview中搜索 [英] create search TextField field to search in a javafx tableview

查看:1010
本文介绍了创建搜索TextField字段以在javafx tableview中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含许多列的 TableView ,我想添加一个搜索字段来过滤符合特定条件的行,按名称搜索作为示例。谢谢

Say I have a TableView with many columns, and I want to add a search field to filter rows that fit certain criteria, search by name as an example . thank you

推荐答案

假设您有 TableView 名为 myTable 填充 myObject 对象 s。
创建一个TextField,在这种情况下我将其命名为filterField,所以这里是一个简单的实现。

Say you have a TableView called myTable filled with myObject Objects. Create a TextField, in this case I named it filterField, so here is a simple implementation.

FilteredList<myObject> filteredData = new FilteredList<>(data, p -> true);

        // 2. Set the filter Predicate whenever the filter changes.
        filterField.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredData.setPredicate(myObject -> {
                // If filter text is empty, display all persons.
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }

                // Compare first name and last name field in your object with filter.
                String lowerCaseFilter = newValue.toLowerCase();

                if (String.valueOf(myObject.getFirstName()).toLowerCase().contains(lowerCaseFilter)) {
                    return true;
                    // Filter matches first name.

                } else if (String.valueOf(myObject.getLastName()).toLowerCase().contains(lowerCaseFilter)) {
                    return true; // Filter matches last name.
                } 

                return false; // Does not match.
            });
        });

        // 3. Wrap the FilteredList in a SortedList. 
        SortedList<myObject> sortedData = new SortedList<>(filteredData);

        // 4. Bind the SortedList comparator to the TableView comparator.
        sortedData.comparatorProperty().bind(myTable.comparatorProperty());
        // 5. Add sorted (and filtered) data to the table.
        myTable.setItems(sortedData);

这篇关于创建搜索TextField字段以在javafx tableview中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆