英文:
How to get the instance of the text field which has triggers the focus listener in JavaFX
问题
我有一个由三个文本字段组成的表单。当表单被提交时,我会验证每个文本字段的值,以确保它符合特定条件。如果某个值无效,我会将相应文本字段的边框颜色
更改为红色。现在,我希望如果用户选择一个文本字段并尝试修改其值,将边框颜色更新回黑色。
为了简化所有文本字段的处理过程,我打算将相同的更改侦听器
附加到每个文本字段上。然而,挑战在于获取每个文本字段的引用,以便我可以在侦听器内部针对它进行特定目标。
keyWord.focusedProperty().addListener(textFieldFocusListener);
date.focusedProperty().addListener(textFieldFocusListener);
location.focusedProperty().addListener(textFieldFocusListener);
ChangeListener<Boolean> textFieldFocusListener = (observable, oldValue, newValue) -> {
// 如果被选中/聚焦,将文本字段的边框颜色更改为黑色
};
英文:
I have a form consisting of three text fields
. When the form is submitted, I validate each text field value to ensure it meets specific conditions. If a value is invalid, I change the border color
of the respective text field to red. Now, I want to update the border color back to black if the user selects a text field and attempts to modify its value.
To streamline the process for all text fields, I aim to attach the same change listener
to each one. However, the challenge lies in obtaining a reference to each text field so that I can specifically target it within the listener.
keyWord.focusedProperty().addListener(textFieldFocusListener);
date.focusedProperty().addListener(textFieldFocusListener);
location.focusedProperty().addListener(textFieldFocusListener);
ChangeListener<Boolean> textFieldFocusListener = (observable, oldValue, newValue) -> {
// Change the border color of the text field to black if it is selected/focused
};
答案1
得分: 3
为什么不只是编写一个方法来创建和注册每个文本字段的监听器?
private void addListenerToTextField(TextField textField) {
textField.focusedProperty().addListener((observable, oldValue, newValue) -> {
// 根据需要处理 textField
});
}
这样可以扩展到多个文本字段,方法相同:
addListenerToTextField(keyWord);
addListenerToTextField(date);
addListenerToTextField(location);
或者
Stream.of(keyWord, date, location).forEach(this::addListenerToTextField);
英文:
Why not just write a method to create and register a listener for each text field?
private void addListenerToTextField(TextField textField) {
textField.focusedProperty().addListener((observable, oldValue, newValue) -> {
// do whatever you need with textField
});
}
Which scales to multiple text fields in the same way
addListenerToTextField(keyWord);
addListenerToTextField(date);
addListenerToTextField(location);
or
Stream.of(keyWord, date, location).forEach(this::addListenerToTextField);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论