Skip to main content

How to load FXML with values from Preferences in JavaFX?

Please note these forums are being decommissioned and use the new and improved forums at
1 reply [Last post]
Joined: 2007-07-02

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")));

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, userName hasn't yet been instantiated.


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2007-07-02

Okay, I found that I can accomplish what I want by having my controller class implement Initializable and assigning the values to the controls in the initialize() override.

Now my question is: Where do I save the values back to the preferences? I tried doing it in the stage's OnCloseRequest handler, but by the time that gets called all the controls have been deleted already - or at least the @FXML variables have been set to null.