How to load FXML with values from Preferences in JavaFX?

javafx-2

Solution

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" />

Problem

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

Original source