Focus Listener for JavaFX Nodes

I am new to JavaFX. I am really stuck on this question. :( And sorry if my English is bad.

I have two stack panels in my JavaFX program. I want to add a focus listener to both of these stack panels.

It should be such that when I click on one stack, it should activate the focus-derived method for this stack panel.

As soon as I click on another stack, the first panel of the stack should call the lost focus method, and the method of the current focus of the stack should be called. Just like we have focus events in the Swing package.

I have currently tried this:

stackPane.focusedProperty().addListener(new ChangeListener<Boolean>() {

                @Override
                public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                    if (newValue.booleanValue()) {
                        focusGained(stackPane);
                    } else {
                        focusLost(stackPane);
                    }
                }
            });

private void focusGained(StackPane stackPane){
    System.out.println("Focus Gained.");
}

private void focusLost(StackPane stackPane){
    System.out.println("Focus Lost.");
}

I also tried setting the focus trace property on the ie stack panel

stackPane.setFocusTraversable(true);

. , 3 , , .

Focus Gained.
Focus Lost.
Focus Gained.

, .

+2
1

, , . :

root.focusedProperty().addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
    focusState(newValue);
});

private void focusState(boolean value) {
    if (value) {
        System.out.println("Focus Gained");
    }
    else {
        System.out.println("Focus Lost");
    }
}
+1

Source: https://habr.com/ru/post/1654952/


All Articles