Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load FXML with values from Preferences in JavaFX?

Tags:

javafx-2

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

like image 363
Michael Avatar asked Oct 16 '25 05:10

Michael


1 Answers

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" />
like image 139
Sergey Grinev Avatar answered Oct 19 '25 14:10

Sergey Grinev