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 ie
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.
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");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.