RequestFocus in TextField doesn't work

后端 未结 6 1237
隐瞒了意图╮
隐瞒了意图╮ 2021-02-13 02:11

I use JavaFX 2.1 and I created GUI using FXML, in the controller of this GUI I added myTextField.requestFocus();.

But I always get the focus in the other co

6条回答
  •  青春惊慌失措
    2021-02-13 02:22

    This can occur when the Scene property for the Node is not yet set. Alas, the scene property can take a "long" time to be set.

    The child node's scene property lags when a scene is first created, and also, when items are added to some parents, such as a TabPane (oddly some parents seem immune, I'm not sure why).

    The correct strategy, which has always worked for me :

    if (myNode.scene) == null {
        // listen for the changes to the node's scene property,
        // and request focus when it is set
    } else {
        myNode.requestFocus()
    }
    

    I have a handy Kotlin extension function which does this.

    fun Node.requestFocusOnSceneAvailable() {
        if (scene == null) {
            val listener = object : ChangeListener {
                override fun changed(observable: ObservableValue?, oldValue: Scene?, newValue: Scene?) {
                    if (newValue != null) {
                        sceneProperty().removeListener(this)
                        requestFocus()
                    }
                }
            }
            sceneProperty().addListener(listener)
        } else {
            requestFocus()
        }
    }
    

    You can then call it from within you code like so :

    myNode.requestFocusOnSceneAvailable()
    

    Perhaps somebody would like to translate it to Java.

提交回复
热议问题