daprog
daprog

Reputation: 155

JavaFX - how to set default active control

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

Upvotes: 5

Views: 31341

Answers (1)

invariant
invariant

Reputation: 8900

Try wrapping your requestFocus() call with Platform.runLater

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

Upvotes: 10

Related Questions