如何使用JavaFX通过多个文本字段过滤表视图数据?

时间:2018-09-08 02:51:15

标签: javafx

我已经使用单个文本字段进行了过滤。但我想按多个字段过滤表视图。多个字段如文本字段,组合框和日期选择器。

@FXML
private void prop_socity_key(KeyEvent event)
{

    society_name.textProperty().addListener(( observable, oldValue, newValue)->
    {

        property_filter.setPredicate((Predicate<? super Search_field>)(Search_field s_f)->
        {


        if(newValue.isEmpty() || newValue == null)
        {
            return true;
        }
        else if(s_f.getprop_society().contains(newValue))
        {
            return true;
        }
        return false;
        });
    });

    SortedList sort = new SortedList(property_filter);
    sort.comparatorProperty().bind(Property_table.comparatorProperty());
    Property_table.setItems(sort);

}

1 个答案:

答案 0 :(得分:0)

使用FilteredList并将其predicate属性绑定到取决于输入的Predicate

private static <T> void replace(ObservableList<T> list, T oldItem, T newItem) {
    if (oldItem == null) {
        if (newItem != null) {
            list.add(newItem);
        }
    } else {
        int index = list.indexOf(oldItem);
        if (newItem == null) {
            if (index >= 0) {
                list.remove(index);
            }
        } else {
            if (index >= 0) {
                list.set(index, newItem);
            } else {
                list.add(newItem);
            }
        }
    }
}
ObservableList<Predicate<SearchField>> predicates = FXCollections.observableArrayList();
property_filter.predicateProperty().bind(Bindings.createObjectBinding(() -> predicates.isEmpty() ? null : new Predicate<SearchField>() {

    @Override
    public boolean test(SearchField item) {
         for (Predicate<SearchField> predicate : predicates) {
             if (!predicate.test(item)) {
                 return false;
             }
         }
         return true;
    }

}, predicates));

society_name.textProperty().addListener(new ChangeListener<String>() {

    private Predicate<SearchField> predicate;

    @Override
    public void changed(ObservableValue<? extends String> o, String oldValue, String newValue) {
        Predicate<SearchField> oldPredicate = predicate;
        predicate = newValue.isEmpty() ? null : i -> i.getprop_society().contains(newValue);
        replace(predicates, oldPredicate, predicate);
    }

});

comboBox.valueProperty().addListener(new ChangeListener<ItemType>() {

    private Predicate<SearchField> predicate;

    @Override
    public void changed(ObservableValue<? extends ItemType> o, ItemType oldValue, ItemType newValue) {
        Predicate<SearchField> oldPredicate = predicate;
        predicate = ...;
        replace(predicates, oldPredicate, predicate);
    }

});

...