2

I am trying to figure out if there is a way to get a reference to the FXML for a given node.

For example I am dynamically loading views - assume I have a Pane referenced in the current Controller:

private void openView() {
    FXMLLoader loader = new FXMLLoader();
    Parent node = loader.load(this.getClass().getResource("MyView.fxml").openStream());
    pane.getChildren().add(node);
    node.requestFocus();
}

I would like to save which views were open so that I can relaunch them next time the window is open. Something like this:

private void saveOpenViews() {
    pane.getChildren().forEach(child -> {
        String fxmlLocation = child.getFXML();
        etc....
    }
}

I can't seem to find a way to get that back to persist what was open... Was hoping there was a way, other than manually tracking in another place.

Thanks.

purring pigeon
  • 4,141
  • 5
  • 35
  • 68

1 Answers1

1

Store the related fxml information in the node userData when you load the node from fxml, then lookup the userdata when you need to know what fxml the node is related to.

private void openView() {
    FXMLLoader loader = new FXMLLoader();
    URL fxmlLocation = this.getClass().getResource("MyView.fxml");
    Parent node = loader.load(fxmlLocation.openStream());
    node.setUserData(fxmlLocation);
    pane.getChildren().add(node);
    node.requestFocus();
}

private void saveOpenViews() {
    pane.getChildren().forEach(child -> {
        URL fxmlLocation = (URL) child.getUserData();
        etc....
    }
}
jewelsea
  • 150,031
  • 14
  • 366
  • 406
  • When using FXML you will normally have a controller class. Create an abstract controller class that contains the needed getter and setter methods. All your controller will extend this class. Then you can access the controller by using fxmlLoader.getController() and call the setter for the FXML location.You can store the controllers of your opened views in an List. Once the save method is called you only need to iterate over your controllers and get the xml. If you want more flexibility to define the view controller you can use DataFX (http://www.guigarage.com/2014/05/datafx-8-0-tutorials/) – Hendrik Ebbers Jan 23 '15 at 07:53
  • Thanks for information Hendrik. Probably best to provide answers as answers rather than comments. – jewelsea Jan 23 '15 at 18:32