2017-06-01 139 views

回答

2

假設你有一個TableViewmyTable填充myObjectObject s。 創建一個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); 
+0

夠說!非常感謝你 –