JavaFX: Focusing textfield programmatically

女生的网名这么多〃 提交于 2019-11-30 01:15:16

问题


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 switched off focusability of all nodes :

for(Node n : children) {
     n.setFocusTraversable(false);

Now I have some textfields, checkboxes, and buttons. I would like to change the state of my input controls (textfield, checkbox,..) programatically: for example I would like to enter the textfield to edit the content programatically. So my question is: how to enter in a non-focus-traversable textfield? Because textfield.requestFocus(); doesn't work anymore since I set false to focustraversable property of my textfield.

Thanks


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/20049452/javafx-focusing-textfield-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!