JavaFX - 在自定义节点上设置 focusedProperty 监听器

JavaFX - Setting focusedProperty Listener on a custom node

我有一个自定义的 TimePicker 节点,它大部分时间都在工作,但我需要能够添加一个侦听器来检查它何时获得或失去焦点。问题是当我专注于它时它没有检测到。

public class TimePicker extends HBox {
    private NumberField nbxH; // NumberField is a custom class that extends Textbox. `focusedProperty().addListener` works as expected for this node.
    private Label lblColon;
    private NumberField nbxM;
    private Button btnAmPm;

    public TimePicker() {
        // for testing
        this.focusedProperty().addListener((observable, oldValue, newValue) -> {
            printDebug("--TIME PICKER FOCUSED PROPERTY-------------------------"
                    + "\n" + observable 
                    + "\n" + oldValue 
                    + "\n" + newValue 
                    );
        });

        nbxH = new NumberField();
        /* nbxH setup */

        lblColon = new Label(":");

        nbxM = new NumberField();
        /* nbxM setup */

        btnAmPm = new Button("AM");
        /* btnAmPm setup */
    }

    /* other methods */
}

当在 class 本身时,我可以检查是否每个 children 都被聚焦。我想添加一个侦听器来检查 children 中的任何一个是否被聚焦,或者 children 中的 none 是否被聚焦。换句话说,如果 children 中的任何一个被聚焦,那么 isFocused 就是 true,如果其中 none 个被聚焦,那么 isFocused 就是 false;我可以设置一个侦听器来检查它是否发生了变化。问题是,isFocused 被设置为最终的并且不能被覆盖。

我明白了。为每个子元素添加一个侦听器,检查是否有任何元素获得焦点并将父元素的焦点设置为结果。一旦我意识到 setFocused 是一个选项,这就变得很明显了。

nbxM.focusedProperty().addListener((observable, oldValue, newValue) -> {
    this.setFocused(nbxH.isFocused() | nbxM.isFocused() | btnAmPm.isFocused());
});