如果节点树中的某个节点获得焦点,则为事件



假设我们有一个节点树,如下所示:

          VBox
           |
         /   
      Pane SplitPane 
     /              
    HBox             Pane
  /                  |
Button   Button   TextField  

当此树的任何节点获得焦点时获取事件的最佳方法是什么(无需在每个节点上设置侦听器(?

例如,

您可以使用ScenefocusOwnerProperty

场景的当前焦点所有者节点。

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;
}

最新更新