Focus Listener for JavaFX Nodes


Question

I am a beginner in JavaFX. I am really stuck at this point. :( And sorry if my English is poor.

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

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

Once I click on another stack pane, the 1st stack pane should give a call to its focus lost method, and the current stack pane's focus gained method should be called. Just like we have focus events in the Swing Package.

Currently I have 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 have also tried to set the focus traversable property on the stack pane i.e.

stackPane.setFocusTraversable(true);

These are not working properly. When I run it, the output only shows these 3 lines, no matter how many times I click on the stack panes.

Focus Gained.
Focus Lost.
Focus Gained.

Please help.

1
3
2/15/2014 1:28:04 PM

Well, it's a bit late but it might help others. This works fine:

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");
    }
}
4
6/1/2016 1:37:18 AM

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