JavaFX: Focusing textfield programmatically

后端 未结 2 814
不知归路
不知归路 2021-01-03 22:44

I wrote an application with JavaFX which will only be usable with keyboard\'s arrows. So I prevented MouseEvent on Scene\'s stage, and I \"listen\" to KeyEvents. I also swit

相关标签:
2条回答
  • 2021-01-03 23:04

    set the .requestFocus(); on initialize method to fire on .fxml file loading controller

    @Override
    public void initialize(URL url, ResourceBundle rb) {
    /* the field defined on .fxml document  
    @FXML
    private TextField txtYear;
    */
    txtYear.requestFocus();
    }
    
    0 讨论(0)
  • 2021-01-03 23:20

    By

    n.setFocusTraversable(false);
    

    the node is made non-focus-traversable instead of non-focusable. It can still be focused for example by mouse or programmatically. Since you prevented mouse events, here the other option:

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            textfield.requestFocus();
        }
    });
    
    Scene scene = new Scene(root);
    

    EDIT: as per comment,
    The javadoc of requestFocus states:

    ... To be eligible to receive the focus, the node must be part of a scene, it and all of its ancestors must be visible, and it must not be disabled. ...

    So this method should be called after construction of scene graph as follow:

    Scene scene = new Scene(root);
    textfield.requestFocus();
    

    However, Platform.runLater in the above will run at the end, after the main method start(), which ensures the call of requestFocus will be after scene graph cosntruction.

    There maybe other reasons depending on the requestFocus implementation code.

    0 讨论(0)
提交回复
热议问题