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
};
>Solution :
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);