[英]How to fire a Textfield listener in JavaFX?
In Java, I'm trying to fire a Textfield listener.在 Java 中,我试图触发一个 Textfield 侦听器。
The only solution I've found is to use setText with a space:我发现的唯一解决方案是使用带有空格的 setText:
txt.setText(" ");
What is the correct way to do it?正确的做法是什么?
Details:细节:
TextField txt = new TextField();
txt.setPromptText("Search");
txt.textProperty().addListener(new ChangeListener() {
public void changed(ObservableValue observable, Object oldVal,Object newVal) {
//...to do
}
};
txt.setText(" "); //Firing the listener
Invoking a stored listener reference调用存储的侦听器引用
You could record a reference to the listener and invoke that whenever you want, for example:您可以记录对侦听器的引用并随时调用,例如:
TextField txt = new TextField();
txt.setPromptText("Search");
ChangeListener<String> txtListener =
(observable, oldValue, newValue) ->
System.out.println(
"Search text updated to: " + newValue
);
txt.textProperty().addListener(
txtListener
);
txtListener.changed(
txt.textProperty(),
null,
"frobozz"
);
This will output " Search text updated to: frobozz
".这将输出“
Search text updated to: frobozz
”。 What I don't much like about this is that it doesn't carry a lot of semantic meaning and the text hasn't really changed.我不太喜欢这个的地方是它没有太多的语义含义,文本也没有真正改变。
Alternate approach替代方法
An alternate approach is to have a function which is named related to your application and invoke that whenever you want either inside or outside the listener.另一种方法是使用与您的应用程序相关的命名函数,并在您想要在侦听器内部或外部随时调用该函数。 I prefer this alternate approach.
我更喜欢这种替代方法。
txt.textProperty().addListener(
(observable, oldValue, newValue) -> search(newValue)
);
search(null);
. . .
private void search(String searchText) {
System.out.println(
"Search result for: " + searchText
);
}
This will output: " Search result for: null
".这将输出:“
Search result for: null
”。
Note: this answer used Java 8 code .注意:此答案使用Java 8 代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.