javajavafxnetbeansfxmlpane

Is there a way to load multiple fxml in array and then showing one of them if button is pressed without reloading same fxml in javaFX?


Netbeans IDE 8.2.

My program has a left menu bar inserted in a VBox.

When i click one of left menu button, my program load in the same stage another controller (with another .fxml of course). And it's ok.

This is how it looks

view main controller

Problem

If i start to make some changes in this new controller, and then I want to open another controller by clicking on left menu button, my "old" controller disappear (it's ok). But when i open again the old controller every change that i've had in that page are disappear.

Because I know, every time button menu's pressed it run this:

    @FXML
public void btnMenuOnAction(ActionEvent event) {
    if (event.getTarget() == btnDashboard) 
    {
        Pane newPane = null;
        try {
            newPane = FXMLLoader.load(getClass().getResource("Dashboard_View.fxml"));
        } catch (IOException ex) {
            System.out.println("Error pane Dashboard");
        }
        pane.getChildren().set(0, newPane);
    } 
    else if (event.getTarget() == btnProduction)
    {
        Pane newPane = null;
        try {
            newPane = FXMLLoader.load(getClass().getResource("Prod_View.fxml"));
        } catch (IOException ex) {
            System.out.println("Error pane Prod");
        }
        pane.getChildren().set(0, newPane);
    }
}

When a user selects a category from menu, I need to be able to edit the settings on the right, switch to another category and make more changes. If I return to the first category, the changes made there persist. So each time user changes categories, the FXMLLoader reloads the FXML file and controller, resetting all controls within to their default values.

So is it possible to reuse an FXML file that has already been loaded and altered? How can I load every fxml before my program starts and just make it visibile inside my Pane when buttons clicked?

gif program to explain my problem


Solution

  • You have to create each FXML file on startup (or on first demand), and simply set the pane to the same instance each time.

    E.g.

    Pane dashboardViewPane;
    Pane prodViewPane;
    

    In initialisation

    dashboardViewPane = FXMLLoader.load(getClass().getResource("Dashboard_View.fxml"));
    prodViewPane = FXMLLoader.load(getClass().getResource("Prod_View.fxml"));
    

    Then

    @FXML
    public void btnMenuOnAction(ActionEvent event) {
        if (event.getTarget() == btnDashboard) 
        {
            pane.getChildren().clear();
            pane.getChildren().add(dashboardViewPane);
        } 
        else if (event.getTarget() == btnProduction)
        {
            pane.getChildren().clear();
            pane.getChildren().add(prodViewPane);
        }
    }