Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the instance of the text field which has triggers the focus listener in JavaFX

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

     };

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading