假设我们有一个节点树,如下所示:
VBox
|
/
Pane SplitPane
/
HBox Pane
/ |
Button Button TextField
当此树的任何节点获得焦点时获取事件的最佳方法是什么(无需在每个节点上设置侦听器(?
例如,
您可以使用Scene
的focusOwnerProperty
:
场景的当前焦点所有者节点。
scene.focusOwnerProperty().addListener((obs, oldval, newval) ->
System.out.println(checkFocus(vbox)));
其中checkFocus
递归检查节点的focusedProperty
源自VBox
:
private boolean checkFocus(Parent p) {
if (!p.isFocused()) {
for (Node node :p.getChildrenUnmodifiable()) {
if (node instanceof Parent && checkFocus((Parent) node))
return true;
else if (node.isFocused())
return true;
}
} else
return true;
return false;
}