Javafx Textfield听众从未被调用
我有一个简单的对话框,其中一些文本字段,我想将一个简单的侦听器添加到Textfield的属性中。应该是一个不介意的,但似乎从来没有称呼它。调试表明,添加了听众(我认为),但没有任何作用。我的感觉是它收集了垃圾。问题是,为什么?
PS。添加setonKeypressed处理程序确实可以正常工作,就像上面的所有其他操作一样。
这是我的班级:
public class MyClass {
@FXML
private TextField emailTextField;
@FXML
private TextField codeTextField;
@FXML
private TextField nameTextField;
private static final Logger LOG = Logger.getLogger(StageController.class.getName());
@FXML
private void initialize() {
emailTextField.onKeyPressedProperty().addListener((observable, oldValue, newValue) -> {
LOG.info("Hi!");
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在将
ChangElistener
添加到onkeypressed
属性。此属性本身就是一个事件处理程序,可以响应密钥按下,而您的代码表示每当onkeypressed
属性更改时,即任何时间setOnKeypresse(...)
或> onkeypressedproperty()。设置(...)
被调用,调用您的侦听器。因此,您的侦听器永远不会被调用,因为
onkeypressedproperty()
永远不会更改。您可能不想响应
onkeypressedproperty()
的更改,而是(也许)想实际响应按键按下。您可以通过设置onkeypressed
属性,或添加另一个事件处理程序来做到这一点。要么:
或:
即使这也不是您想要的。文本字段已经知道按下键时该怎么办。根据密钥,它可能会更改文本。您通常想做的是响应文本更改:
这将响应文本更改,无论它们是否是由于钥匙按下而发生的(例如,它会响应用鼠标粘贴的用户粘贴文本),但不会响应键按不更改任何内容的按下(例如,按 shift 或 ctrl ,或 delete 当文本字段为空时)。
You're adding a
ChangeListener
to theonKeyPressed
property. This property is itself an event handler which responds to key presses, and your code means that whenever theonKeyPressed
property changes, i.e. any timesetOnKeyPressed(...)
oronKeyPressedProperty().set(...)
is called, your listener is invoked.So your listener is never invoked because the
onKeyPressedProperty()
never changes.You probably don't want to respond to changes in the
onKeyPressedProperty()
, but instead (perhaps) want to actually respond to key presses. You do this by either setting theonKeyPressed
property, or adding another event handler.Either:
or:
Even this is likely not what you want. The text field already knows what to do when a key is pressed; depending on the key it may change the text. What you more typically want to do is respond to the text changing:
This will respond to text changes, whether or not they occur due to key presses (e.g. it will respond to the user pasting text with the mouse) but will not respond to key presses that don't change anything (e.g. pressing SHIFT or CTRL, or DELETE when the text field is empty).