JavaFx: how to reference main Controller class instance from CustomComponentController class?

前端 未结 2 867
清歌不尽
清歌不尽 2021-01-15 19:08

WHAT I HAVE is a standard JavaFX application: Main.java, MainController.java & main.fxml. To add custom component, I created CustomComponentController

相关标签:
2条回答
  • 2021-01-15 19:15

    Your problem looks like the classic catalog-crud forms updating, I implemented an interface that I called Updatable with an update method so I could reference any catalog form with any crud form easy after passing Controller Main Class as the UserData Property of the Child Root Component's Form

    Hope it Can Solve your problem

    0 讨论(0)
  • 2021-01-15 19:23

    The problem can be solved if you comply the following conditions:

    1. Not only public, but obligatory static MainController mc should be.

    2. Do not forget id in fxml for CustomComponentController: <CustomComponentController fx:id="cc"/>, where cc is the name of the "@FXML imported" CustomComponentController in your MainController class.

    3. Omit parameter fx:controller="main.CustomComponentController" in custom_component_controller.fxml as it results in "Controller value already specified" error (a conflict between main.fxml and custom_component_controller.fxml markup declared controllers).

    4. Put mc = this; in the beginning of MainController's initialize() method. Before using mc in CustomComponentController class, check if it's not null. It can be null when all components, including CustomComponentController, are instantiated at application startup, but there is no mc instance yet. MainController method initialize() where MainController is instantiated is called after components are loaded. Therefore better practice is to use approach in the next paragraph.

    5. In main.fxml create primary component of the same type that CustomComponentController and with the only fx:id parameter. Replace primary component with your CustomComponentController by creating reloadCustomComponents() method and calling it from CustomComponentController's initialize() method. Do it by adding the following to reloadCustomComponents() method:

      customComponentAnchorPane.getChildren().remove(customComponent);

      customComponent = new customComponent();

      customComponentAnchorPane.getChildren().add(customComponent);

    Thus all components can be placed outside CustomComponentController with all their methods and reloaded at the startup of the apllication. All component declarations stay in MainController class and can be reached through MainController mc reference. No duplicate creating of components in detail with parameters is needed.

    0 讨论(0)
提交回复
热议问题