Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX access parent Controller class from FXML child

Tags:

java

javafx

fxml

using JavaFX for an application and I have a Main.fxml file with some fxml child files inside it.

I would like to access to MainController class of Main.fxml from the child Controllers.

I'll try to explain better with an example:

MainFxml:

    <HBox fx:controller="MainController.java">
        <fx:include source="child.fxml"/>
    </HBox>

MainController:

    public class MainController implements Initializable {
            private String string;
            public void setString (String string) {
                    this.string = string;
            }

ChildFxml:

    <HBox fx:id="child" fx:controller="ChildController.java">
        <Button text="hello" onAction="#selectButton"></Button>
    </HBox>

ChildController:

    public class ChildController implements Initializable {
            @FXML HBox child;
            @FXML Button button;
            @FXML
            public void selectButton (ActionEvent event) {
                // here call MainController.setString("hello");
            }

I tried this solution found on StackOverflow but I need to get the Controller reference of the Main.fxml that has been already loaded. Is there any method to get the Controller starting from a specific Pane? Something like:

    // child.getParent().getController();
like image 652
piealoisi Avatar asked Jun 28 '17 16:06

piealoisi


1 Answers

If you assign a fx:id to the <fx:include> tag, FXMLLoader tries to inject the the controller of the included fxml to a field named <fx:id>Controller. You can pass the MainController reference to the child controllers in the initialize method:

<HBox fx:controller="MainController.java">
    <fx:include fx:id="child" source="child.fxml"/>
</HBox>

MainController

@FXML
private ChildController childController;

@Override
public void initialize(URL url, ResourceBundle rb) {
    childController.setParentController(this);
}

ChildController

private MainController parentController;

public void setParentController(MainController parentController) {
    this.parentController = parentController;
}

@FXML
private void selectButton (ActionEvent event) {
    this.parentController.setString("hello");
}

It would however be better practice to keep the ChildController independent from the parent. This could be done by providing a StringProperty in the ChildController that gets set to the value the parent should display.

ChildController

private final StringProperty value = new SimpleStringProperty();

public StringProperty valueProperty() {
    return value;
}

@FXML
private void selectButton (ActionEvent event) {
    value.set("hello");
}

ParentController

@Override
public void initialize(URL url, ResourceBundle rb) {
    childController.valueProperty().addListener((observable, oldValue, newValue) -> setString(newValue));
}
like image 171
fabian Avatar answered Nov 19 '22 23:11

fabian