Skip to main content

How to load FXML with values from Preferences in JavaFX?

1 reply [Last post]
michaelberkowitz
Offline
Joined: 2007-07-02
Points: 0

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

Reply viewing options

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

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.