JavaFX - how to set default active control


Question

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).

1
5
11/12/2012 9:36:34 PM

Try wrapping your requestFocus() call with PlatForm.runlater

Platform.runLater(new Runnable() {
    public void run() {
        textField.requestFocus();
    }
});
11
7/2/2016 12:21:05 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon