简体   繁体   中英

JavaFX - Access parent fx:id from child

Let's say I have a button in a nested (child) fxml file, and in the child's controller I have created an action event that fires on button click. From that method I want to disable or enable certain controls (for instance some tabs in a tabpane) in my main (parent) fxml.

How can I achieve this?

This is the closest thread I found, which discussed how to do it the other way around: JavaFX - Access fx:id from nested FXML

Any help is greatly appreciated!

Define an observable property in the nested controller, and observe it from the surrounding controller:

public class ChildController {

    private final BooleanProperty stuffShouldBeDisabled = new SimpleBooleanProperty();

    public BooleanProperty stuffShouldBeDisabledProperty() {
        return stuffShouldBeDisabled ;
    }

    public final boolean getStuffShouldBeDisabled() {
        return stuffShouldBeDisabledProperty().get();
    }

    @FXML
    private void handleButtonClick(ActionEvent event) {
        stuffShouldBeDisabled.set( ! stufShouldBeDisabled.get() );
    }

    // ...
}

and then in the "surrounding" (Parent) controller (ie the controller for the FXML file with the <fx:include> tag):

public class MainController {

    @FXML
    private ChildController childController ; // injected via <fx:include fx:id="child" ... />

    @FXML
    private Tab someTab ;

    public void initialize() {
        childController.stuffShouldBeDisabledProperty().addListener((obs, wasDisabled, isNowDisabled) -> {
            someTab.setDisable(isNowDisabled);
        }
    }

    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM