如何在JavaFX中获取触发焦点监听器的文本字段实例。

huangapple go评论65阅读模式
英文:

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&lt;Boolean&gt; textFieldFocusListener = (observable, oldValue, newValue) -&gt; {

        // 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) -&gt; {
        // 根据需要处理 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) -&gt; {
        // 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);

huangapple
  • 本文由 发表于 2023年6月8日 01:37:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定