0

I have a Java FX application with has a main view (FXML) and its controller. I am trying to simulate a tabpane like child views(FXML) with their own controllers. So far so good, I am able to switch between the child views with the following code :

//page type para is the path of FXML file
private void changePage(String pageType) throws IOException
{
    childScene.getChildren().clear();
    FXMLLoader loader = new FXMLLoader(getClass().getResource(pageType));

    loader.setControllerFactory((Class<?> controllerClass) ->
    {
        //trying to load a single instance controller of the child
        if (controllerClass == EngTaiController.class)
        {
            eng2TaiController.setData(words, selectedFont);
            return eng2TaiController;
        }
        try
        {
            return controllerClass.newInstance();
        }catch (Exception ex)
        {
            throw new RuntimeException(ex);
        }
    });
    Parent page = loader.load();
    VBox.setVgrow(page, Priority.ALWAYS);
    //childScene is the container for childviews
    childScene.getChildren().add(page);
}

The problem is that it doesn't persist any user state, text in textboxes, selection in list view, loaded custom controls in child views when switched from one view to another.

M. Ko
  • 563
  • 6
  • 31
  • 1
    Reusing a single controller instance each time you reload an FXML file seems like a bad idea (if you have two views open at once, loaded from the same FXML file, the controller will only have references to the UI components from the last one loaded). Why would you expect this to persist the state of your view? Typically to persist state across views you share a single model instance with all the controllers. – James_D Feb 28 '17 at 13:53
  • So it would seem. I thought a controller should be associated with only one view. You have a point, persisting user states into one model and bind to views and controllers is a workaround. It would be more appropriate to think `JavaFX` like web MVC pattern rather than traditional software component. Cause I am migrating from .net framework. Aye? – M. Ko Mar 01 '17 at 02:21

0 Answers0