I've a JavaFX application with multiple controllers. The controllers must comunicate each other to manipulate view objects. There is a root controller for the root view and many sub-controllers, each for it's own sub-view. My question it's about the best design for this structure. For now I've organized things like this:
- RootController has references to each subcontroller;
- Each subController has references to it's own subView objects and handles events from this objects;
- When an action on view object A (may be a Button) in subView A must effects a B in subView B, subController A mantain reference to a ChangeListener A1 that is defined and injected, during initialization, from rootController; the ChangeListener calls the subController B's method to act on viewObject B; eventually rootController can act on its own viewObjects in the ChangeListener.
I'll show an example:
public SubControllerA {
private Model model;
//button defined in subView A
@FXML
private Button buttonA;
//Can be an user-defined interface, actually I used ChangeListener from JavaFX
private ChangeListener listenerA;
private void setModel(Model model){
this.model=model;
}
private void setListenerA(ChangeListener listener) {
this.listenerA=listener;
}
//method to handle buttonA click
@FXML
private void handleButtonAClick(){
doSomethingOnSubViewA();
listener.changed();
}
}
public SubControllerB {
private Model model;
//label defined in subView B
@FXML
private Label labelB;
private void setModel(Model model){
this.model=model;
}
private void doSomethingOnLabelB(){
label.setText("button A clicked!");
}
}
public RootController {
private Model model;
@FXML
private BorderPane mainPanel;
@FXML
private SubControllerA subControllerA;
@FXML
private SubControllerB subControllerB;
//initialize listeners
@FXML
public void initialize() {
this.model = new Model();
subControllerA.setModel(model);
subControllerB.setModel(model);
subControllerA.setListenerA(new ChangeListener(){
public void changed() {
doSomethingOnMainPanel();
subControllerB.doSomethingOnLabelB();
}
}
}
}
Do you think this is a correct design? Do you have any suggestion to improve it?
Thanks