Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus Listener for JavaFX Nodes

Tags:

java

swing

javafx

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.

like image 476
Anmol Mahatpurkar Avatar asked Feb 15 '14 13:02

Anmol Mahatpurkar


1 Answers

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) {
    System.out.println(value ? "Focus gained" : "Focus lost");
}
like image 112
Danny E.K. van der Kolk Avatar answered Oct 20 '22 04:10

Danny E.K. van der Kolk