简体   繁体   English

JavaFX节点的Focus Listener

[英]Focus Listener for JavaFX Nodes

I am a beginner in JavaFX. 我是JavaFX的初学者。 I am really stuck at this point. 我真的被困在这一点上。 :( And sorry if my English is poor. :(对不起,如果我的英语很差。

I have two stack panes in my JavaFX program. 我的JavaFX程序中有两个堆栈窗格。 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. 一旦我点击另一个堆栈窗格,第一个堆栈窗格应该调用它的焦点丢失方法,并且应该调用当前堆栈窗格的focus gain方法。 Just like we have focus events in the Swing Package. 就像我们在Swing包中有焦点事件一样。

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. 当我运行它时,输出只显示这3行,无论我点击堆栈窗格多少次。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM