I'm new to JavaFX. I'm having troubles with controllers.
I have two GUIs, called A and B, each one with its controller (ControllerA and ControllerB).
My program is pretty simple: it starts by opening A, and there's a button that opens B when pressed. Viceversa, B has a button that opens A.
ControllerA has one method, called "openA", and ControllerB has one method called "openB".
So, A needs a ControllerB to open B, and viceversa again.
I watched a tutorial and the way he deals with controller communication is the following:
public class ControllerA{
public void onPressingButtonB(ActionEvent e) throws IOException{
FXMLLoader loaderB = new FXMLLoader(getClass().getResource("class-b.fxml"));
root = loaderB.load();
ControllerB controllerB = loaderB.getController();
controllerB.openB(e);
}
But this seems 'not optimal' to me. Everytime i'm in A and want to go to B, i need to reistantiate the ControllerB. So, i declared that ControllerA has a ControllerB, and used the following code:
public class ControllerA{
private ControllerB controllerb;
{
try {
controllerb = loadControllerB();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public ControllerB loadControllerB() throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("class-b.fxml"));
root = loader.load();
return loader.getController();
}
public void onPressingButtonB(ActionEvent e) throws IOException{
controllerb.openB(e);
}
This way, my action listener can be resolved to one line, having istantiated the controller directly in my class, and it works like a charm.
Thing is... of course i need to do it specularly with ControllerB, but this leads to a major problem: if ControllerA istantiate a ControllerB when created, and ControllerB istantiate a ControllerA when created... it's a loop. In fact, it loops and gives me error on the load method.
My question is: is there a way to fix my code and creating controllers just one time (so my action listener can be just one line of code), or i have to reistantiate controllers every time i have to use them?
Thank you very much.