Bart
Bart

Reputation: 59

Java FXML Loading a view for later use

I want to load a FXML view into my program and save the view for later use.

I currently have a Pane that switches out FXML files.

@FXML private Pane contentPane;
@FXML 
public void toHome() {
   contentPane.getChildren().setAll(FXMLLoader.load(getClass().getResource("../fxml/Home.fxml")));
}
@FXML 
public void toBrowse() {
   contentPane.getChildren().setAll(FXMLLoader.load(getClass().getResource("../fxml/Browse.fxml")));
}

The thing is that I have text fields on each of the new FXML pages and when I switch pages, I don't want it to create a new FXML reference and lose the data in that text field. How can I keep the original page that I set?

Thanks,

Bart

Upvotes: 1

Views: 1316

Answers (1)

beosign
beosign

Reputation: 433

I think you can use a cache here. So basically, store the loaded fxml in a hashmap.

If it not in there, load it and store it into the hashmap, otherwise grab it from the hashmap and use it. This post explains that it is fine to cache loaded FXML objects, for example when it comes to performance, see chapter "Cache FXML load node trees and controllers" that is mentioned there.

private static Map<String, Object> map = new HashMap<>();

@FXML
private Pane contentPane;

@FXML
public void toHome() throws IOException {
    Object loaded = map.get("home");
    if (loaded == null) {
        loaded = FXMLLoader.load(getClass().getResource("../fxml/Home.fxml"));
        map.put("home", loaded);
    }

    contentPane.getChildren().setAll((Node) loaded);
}

(I had to insert a cast to Node, otherwise it didn't compile. I'm not sure whether this is always correct)

Upvotes: 2

Related Questions