【问题标题】:JavaFx: how to reference main Controller class instance from CustomComponentController class?JavaFx:如何从 CustomComponentController 类中引用主控制器类实例?
【发布时间】:2023-03-04 00:42:01
【问题描述】:

我拥有的是一个标准的 JavaFX 应用程序:Main.java, MainController.java & main.fxml。为了添加自定义组件,我创建了CustomComponentController.javacustom_component_controller.fxml

问题是在CustomComponentController 方法中我需要引用MenuController 中的其他方法和标准组件。我将public static MainController mc; 添加到MainController 类主体中,以便可以从CustomComponentController (MainController.mc.neededMethod()) 中看到它。然后我尝试在 MainController.initialize() 方法 (mc = this;) 中将所有内容传递给它 - 在调试此断点时,我看到 this 充满了组件实例,但之后 mc 仍然是空组件。

问题是如何引用MainController 的运行实例以在其他类中使用其组件和方法,并相互交叉引用不同的自定义组件?如何将MainController代码从组件的事件处理程序和辅助方法中全部移到组件自己的类中?

我尝试了以下方法,但没有办法让它们正常工作:

Accessing FXML controller class

How can I access a Controller class in JavaFx 2.0?

JavaFX 2.0 + FXML. Updating scene values from a different Task

JavaFX 2.2 -fx:include - how to access parent controller from child controller

【问题讨论】:

    标签: reference controller javafx instance custom-component


    【解决方案1】:

    满足以下条件即可解决问题:

    1. 不仅是公开的,而且应该是强制性的静态MainController mc

    2. 不要忘记 CustomComponentController 的 fxml 中的 id:<CustomComponentController fx:id="cc"/>,其中 cc 是 MainController 类中“@FXML 导入”CustomComponentController 的名称。

    3. custom_component_controller.fxml 中省略参数fx:controller="main.CustomComponentController",因为它会导致“控制器值已指定”错误(main.fxmlcustom_component_controller.fxml 标记声明的控制器之间存在冲突)。

    4. mc = this; 放在MainControllerinitialize() 方法的开头。在 CustomComponentController 类中使用 mc 之前,请检查它是否不为空。当应用程序启动时实例化所有组件,包括CustomComponentController,但还没有 mc 实例时,它可以为 null。 MainController 方法 initialize() 实例化 MainController 在组件加载后调用。因此,更好的做法是在下一段中使用方法。

    5. main.fxml 中创建与CustomComponentController 相同类型的主组件,并使用唯一的fx:id 参数。通过创建reloadCustomComponents() 方法并从CustomComponentControllerinitialize() 方法调用它,用您的CustomComponentController 替换主要组件。通过将以下内容添加到 reloadCustomComponents() 方法来做到这一点:

      customComponentAnchorPane.getChildren().remove(customComponent);

      customComponent = new customComponent();

      customComponentAnchorPane.getChildren().add(customComponent);

    因此,所有组件都可以放在CustomComponentController 之外及其所有方法,并在应用程序启动时重新加载。所有组件声明都保留在MainController 类中,可以通过MainController mc 引用访问。无需重复创建带参数的详细组件。

    【讨论】:

      【解决方案2】:

      您的问题看起来像经典的目录-crud 表单更新,我实现了一个接口,我用 update method 调用了 Updatable,因此在将 Controller Main Class 作为 @ 传递后,我可以轻松地使用任何 crud 表单引用任何目录表单子根组件的Form 987654324@

      希望它能解决你的问题

      【讨论】:

        猜你喜欢
        • 2016-10-11
        • 1970-01-01
        • 2014-10-18
        • 2012-12-15
        • 2020-05-14
        • 2015-08-29
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        相关资源
        最近更新 更多