1

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

Bart
  • 59
  • 1
  • 1
  • 8

1 Answers1

2

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)

Community
  • 1
  • 1
beosign
  • 433
  • 5
  • 10
  • The map can be Map type. – Uluk Biy Aug 08 '15 at 08:59
  • As per http://stackoverflow.com/questions/13754214/how-to-use-fxmlloader-load-javafx-2 there could be various return types for the load method, so I think it depends on the concrete FXML file – beosign Aug 08 '15 at 09:40
  • 1
    Almost in all cases the fxml file contains some hierarchic structure of nodes. If the top level node is one of layouts then it is safe to cast all types of layouts to `Parent`. Even more safer is to cast to `Node`. Since it is the super class of Parent and all UI controls in JavaFX. Also instead of casting, the desired type can be specified as `Parent parent = FXMLLoader.load( "..." );` – Uluk Biy Aug 08 '15 at 11:44