I'm using what seems to be a typical JavaFX start() method when loading from an FXML file:
    public void start(Stage stage) throws Exception {
    this.stage = stage;
    Scene scene = new Scene(FXMLLoader.<AnchorPane>load(getClass().getResource("layout.fxml")));
    stage.setScene(scene);
    stage.show();
}
I have some variables that correspond to controls, like:
    @FXML private TextField userName;
I would like to initialize userName to a value from the Preferences, as in:
    prefs = Preferences.userRoot().node(this.getClass().getName());
    userName.setText(prefs.get("userName", userName.getText()));
But when can I call this? If I do it before the stage.show(), userName hasn't yet been instantiated.
TIA
Make your Controller implement Initializable and put loading to initialize():
public class Sample implements Initializable {
    @FXML private TextField userName;
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
        userName.setText(prefs.get("userName", userName.getText()));
    }    
}
Also note that your can use ResourceBundle and put your defaults directly to fxml file. Just create my.properties file and use it during loading:
FXMLLoader.load(
    getClass().getResource("layout.fxml"),
    ResourceBundle.getBundle("my"));
then in your fxml you may use properties from my.properties:
<TextField fx:id="userName" text="%userName" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With