javaFX focusHandler?

489 views Asked by At

I am just changing from AWT to JavaFX and im wondering how to work with focus. For Exampe: In AWT I wrote something like that:

Button bFocus = new Button("Focus");
bFocus.addFocusListener(new FocusListener() {

        public void focusGained(FocusEvent e) {
            System.out.println("Having the Focus");
        }

        public void focusLost(FocusEvent e) {
            System.out.println("Lost the Focus");
        }
});

But how does it work in JavaFX? I tried many different things, but that doesnt work...

2

There are 2 answers

0
James_D On

JavaFX has an API that defines observable properties with which you can register listeners and respond when they change. Almost all state that belongs to UI elements in JavaFX is represented by these properties, allowing you to register a listener that responds when they change.

So, for example, the superclass of all UI elements, Node has a ReadOnlyBooleanProperty called focused, with which you can register a listener:

Button bFocus = new Button("Focus");
bFocus.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
    if (isNowFocused) {
        System.out.println("Having the Focus");
    } else {
        System.out.println("Lost the Focus");
    }
});
1
Raj Hirani On

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

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!