You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何监听JavaFX中HTMLEditor的获取与失去焦点事件?

JavaFX HTMLEditor 焦点状态监听解决方案

直接监听HTMLEditor的focusedProperty()之所以无效,是因为HTMLEditor内部实际承载输入的是嵌套的WebView组件,焦点会落在WebView而非HTMLEditor本身上。下面是两种可行的解决方法:

方法一:监听内部WebView的焦点状态

先获取HTMLEditor内部的WebView,再监听它的焦点属性:

// 确保HTMLEditor已加入Scene后再执行lookup
htmlEditor.sceneProperty().addListener((obs, oldScene, newScene) -> {
    if (newScene != null) {
        WebView webView = (WebView) htmlEditor.lookup(".web-view");
        if (webView != null) {
            webView.focusedProperty().addListener((obsFocus, oldVal, newVal) -> {
                if (newVal) {
                    // HTMLEditor实际获取输入焦点
                    System.out.println("HTMLEditor 获取焦点");
                } else {
                    // 失去焦点
                    System.out.println("HTMLEditor 失去焦点");
                }
            });
        }
    }
});

方法二:通过Scene的焦点所有者判断(更准确)

监听Scene的focusOwnerProperty,判断当前焦点是否属于HTMLEditor的子节点:

htmlEditor.getScene().focusOwnerProperty().addListener((obs, oldOwner, newOwner) -> {
    // 判断新焦点是否属于HTMLEditor
    boolean nowFocused = isNodeDescendant(newOwner, htmlEditor);
    // 判断旧焦点是否属于HTMLEditor
    boolean wasFocused = isNodeDescendant(oldOwner, htmlEditor);

    if (nowFocused && !wasFocused) {
        System.out.println("HTMLEditor 获取焦点");
    } else if (!nowFocused && wasFocused) {
        System.out.println("HTMLEditor 失去焦点");
    }
});

// 辅助方法:判断节点是否为目标节点的后代
private boolean isNodeDescendant(Node node, Node target) {
    if (node == null) return false;
    if (node == target) return true;
    return isNodeDescendant(node.getParent(), target);
}

注意事项

  • lookup(".web-view")必须在HTMLEditor被添加到Scene之后调用,否则无法找到对应的WebView组件。
  • 方法一实现简单,但如果WebView内部的子元素转移焦点,可能会触发不必要的回调;方法二更精准,能准确识别整个HTMLEditor区域的焦点变化。

内容的提问来源于stack exchange,提问作者Aleksandr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 21:10:28