我不知道 Kotlin/TornadoFX,但这是您(或其他人)可能能够翻译的 JavaFX 解决方案。
基本思想是创建FilteredList 并将其predicateProperty 绑定到依赖于适当StringProperty 的Predicate。有多种库方法可用于创建此类绑定。例如。你可以这样做:
filteredList = new FilteredList<>(baseList);
filteredList.predicateProperty().bind(
new ObjectBinding<>() {
{
super.bind(prop);
}
@Override
public Predicate<String> computeValue() {
return t -> t.length() > prop.get().length() ;
}
}
);
您还可以使用Bindings.createBinding() 方法,该方法采用Callable<Predicate<String>> 和要观察的可观察对象列表(如果有任何无效,则重新计算):
filteredList.predicateProperty().bind(Bindings.createObjectBinding(
// Callable<Predicate<String>> expressed as a lambda: () -> Predicate<String>
() ->
// Predicate<String> expressed as a lambda: String -> boolean
t -> t.length() > prop.get().length(),
prop
));
如果没有评论,那就简明扼要(但令人难以置信)
filteredList.predicateProperty().bind(Bindings.createObjectBinding(
() -> t -> t.length() > prop.get().length(),
prop
));
这是一个完整的例子:
import static javafx.beans.binding.Bindings.createObjectBinding;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class FilteredListExample extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
ObservableList<String> baseList = FXCollections.observableArrayList("a", "aa", "aaa", "b", "bb", "bbb");
FilteredList<String> filteredList = new FilteredList<>(baseList);
ListView<String> listView = new ListView<>(filteredList);
TextField input = new TextField();
filteredList.predicateProperty().bind(createObjectBinding(
() -> t -> t.length() >= input.getText().length(),
input.textProperty()));
BorderPane root = new BorderPane(listView, input, null, null, null) ;
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) { Application.launch(args); }
}