JavaFX – how to set default active control

javajavafxjavafx-2

I've got single window JavaFX application, created from one of the JavaFX tutorial.

I'm setting new window content by following function:

private Initializable replaceSceneContent(final String fxml) throws Exception {

    // wczytanie fxml
    FXMLLoader loader = new FXMLLoader();
    InputStream in = Main.class.getResourceAsStream(fxml);
    loader.setBuilderFactory(new JavaFXBuilderFactory());
    loader.setLocation(Main.class.getResource(fxml));
    AnchorPane page;
    try {
        page = (AnchorPane) loader.load(in);
    } finally {
        in.close();
    }

    Scene scene = new Scene(page, w, h);
    stage.setScene(scene);
    return (Initializable) loader.getController();
}

But i want to choose one of TextFields from this fxml file to be active by default. How to do this? I've tried to call requestFocus method in controller's initialize method but it didn't work. I haven't found any suitable property in TextField class either in AnchorPane class (AnchorPane is root element of fxml controls tree).

Best Answer

Try wrapping your requestFocus() call with PlatForm.runlater

Platform.runLater(new Runnable() {
    public void run() {
        textField.requestFocus();
    }
});