Jan Lochman
Jan Lochman

Reputation: 469

How to handle Node focus in JavaFX

What Event is called in JavaFX, when a Node is focused?

I have TextField, which can be focused either by mouse (setOnMouseClicked) or by TAB key from other Node (here my problem comes in).

How can I handle the second focus possibility? Is there a way how to handle both at once?

Upvotes: 1

Views: 590

Answers (1)

fabian
fabian

Reputation: 82461

You can listen to the focused property:

TextField tf = new TextField();
TextField tf2 = new TextField();

tf.focusedProperty().addListener((observable, oldValue, newValue) -> {
    if (newValue) {
        System.out.println("Node 1: Mine!");
    }
});
tf2.focusedProperty().addListener((observable, oldValue, newValue) -> {
    if (newValue) {
         System.out.println("Node 2: Mine!");
    }
});

Scene scene = new Scene(new VBox(tf, tf2), 300, 250);

If you change the focus, you can observe see the 2 TextField "arguing who's got the focus".

Upvotes: 1

Related Questions