【问题标题】:create search TextField field to search in a javafx tableview创建搜索 TextField 字段以在 javafx tableview 中搜索
【发布时间】:2017-11-03 05:02:57
【问题描述】:

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

【问题讨论】:

    标签: java search javafx tableview


    【解决方案1】:

    假设您有一个名为myTable 的TableView 填充有myObject Objects。 创建一个TextField,在本例中我将其命名为filterField,所以这里是一个简单的实现。

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      相关资源
      最近更新 更多