How perform task on JavaFX TextField at onfocus and outfocus?


Question

I am working on JavaFX project. I need to perform some task on a JavaFX TextField.

For example on the "on focus" event for the TextField I want to print

System.out.println("Textfield on focus");

and on the "out focus" event it should print

System.out.println("Textfield out focus");
1
44
5/23/2019 2:17:55 PM

Accepted Answer

I thought it might be helpful to see an example which specifies the ChangeListener as an anonymous inner class like scottb mentioned.

TextField yourTextField = new TextField();
yourTextField.focusedProperty().addListener(new ChangeListener<Boolean>()
{
    @Override
    public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue)
    {
        if (newPropertyValue)
        {
            System.out.println("Textfield on focus");
        }
        else
        {
            System.out.println("Textfield out focus");
        }
    }
});

I hope this answer is helpful!

77
6/6/2013 8:05:05 PM

You can use the focusedProperty of Node to attach a ChangeListener.

Extending the answer from Brendan: from JavaFX8 (as it comes with Java 8), a lambda expression combined with a ternary operator can make it really compact:

textField.focusedProperty().addListener((obs, oldVal, newVal) -> 
    System.out.println(newVal ? "Focused" : "Unfocused"));

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon