演示如何侦听文本框内容的变化
public class InstantSearchDemo extends Application {
private TextField textfield;
private ListView<String> listview;
private List<String> words = Arrays.asList(("俄罗斯限制 VPN 和匿名代理工具的的法律于 11 月 1 日正式生效。" +
"俄罗斯没有禁止 VPN 和代理工具,而是要求代理服务商限制用户访问被禁止的网站,也就是说翻墙之后还有一堵墙。VPN 供应商" +
"将需要访问监管机构俄罗斯通讯监管局的被屏蔽网站黑名单。国家杜马信息政策委员会负责人 Leonid Levin 称,法律只是想要" +
"屏蔽“非法内容”,无意对守法公民施加限制。今年 6 月,Google.ru 的一个网页包含了被屏蔽赌博网站的域名,作为惩罚,搜" +
"索引擎被屏蔽了几个小时。俄罗斯的这项法律豁免了企业 VPN,但不清楚俄罗斯通讯监管局如何区分企业和公共 VPN。")
.split("[\\s,。“”]"));
private InstantSearch<String> instantSearch = new InstantSearch<>(words, String::contains);
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(root(), 400, 400));
primaryStage.show();
}
private Parent root() {
textfield = textfield();
listview = listView();
VBox vBox = new VBox(textfield, listview);
vBox.setPadding(new Insets(20));
vBox.setSpacing(10);
return vBox;
}
private TextField textfield() {
TextField textField = new TextField();
textField.textProperty().addListener((observable, oldValue, newValue) -> {
String trimed = newValue.trim();
if (trimed.length() > 0) {
doSearch(trimed);
}
});
return textField;
}
private void doSearch(String keyword) {
List<String> searchResult = instantSearch.search(keyword);
listview.getItems().clear();
listview.getItems().addAll(searchResult);
}
private ListView<String> listView() {
return new ListView<>();
}
///////////////////////////////////////////////
private class InstantSearch<T> {
private Collection<T> tCollection;
private BiFunction<T, String, Boolean> matcher;
public InstantSearch(Collection<T> tCollection, BiFunction<T, String, Boolean> matcher) {
this.tCollection = tCollection;
this.matcher = matcher;
}
public List<T> search(String keyword) {
return (tCollection == null || matcher == null) ?
Collections.emptyList() :
tCollection.stream()
.filter(t -> matcher.apply(t, keyword))
.collect(Collectors.toList());
}
}
}
效果: