0

In my mainController I'm using the following method to change views:

@FXML
public void handleChangeView(ActionEvent event) {
    try {
        String changeButtonID = ((Button) event.getSource()).getId();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("../../resources/view/" + changeButtonID + ".fxml"));
        mainView.setCenter(loader.load());
    } catch (IOException e){
e.printStackTrace();
    }
}

Now this is working but I have two problems:

1) With each button click the controller of the loaded FXML file fires again. For example in my other controller I have:

            Timeline counterTimeline = new Timeline(new KeyFrame(Duration.seconds(1), e -> System.out.println("Test")));
            counterTimeline.setCycleCount(Animation.INDEFINITE);
            counterTimeline.play();

With each click it seems a new Timeline is created and set to play - how can I ensure this doesn't happen? It seems like every time a change view button is clicked the controller for it is re-initialized.

2) How can I ensure each controller can see the model while still using the above method to change views? I'd rather avoid dependancy injections because I honestly can't wrap my head around it - after 6 hours trying to get afterburner.fx to work I can't handle it.

AlwaysNeedingHelp
  • 1,851
  • 3
  • 21
  • 29

1 Answers1

1

You can create a new fxml nodes only once per type:

private final Map <String, Parent> fxmls = new HashMap<>();

@FXML
public void handleChangeView(ActionEvent event) {
   try {
    String changeButtonID = ((Button) event.getSource()).getId();
    Parent newOne = fxmls.get(changeButtonID);
    if (newOne == null) {
      FXMLLoader loader = new FXMLLoader(getClass().getResource("../../resources/view/" + changeButtonID + ".fxml"));
      newOne = loader.load();
      fxmls.put(changeButtonID, newOne):
    }
    mainView.setCenter(newOne);
  } catch (IOException e){
    e.printStackTrace();
  }
}
Sergey Grinev
  • 34,078
  • 10
  • 128
  • 141
  • This works perfectly thank you! Now the only think left is making sure the controllers can see the single model object I have - any suggestions on how it could be done? – AlwaysNeedingHelp Jun 03 '18 at 22:50