初始化控制器和FXML链接控制器之间的区别? [英] Difference between initialized controllers and FXML linked controllers?

查看:235
本文介绍了初始化控制器和FXML链接控制器之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到最近,我才知道你可以在 FXML 文件中设置 fx:controller 的控制器,所以我依靠 FXMLLoader的 setController 来管理链接。

Until recently I didn't know you could set controllers with fx:controller in the FXML file so I have relied on FXMLLoader's setController to manage linking.

那么,是否有任何理由使用一个而不是像可重写的initialize()方法的特定情况会有用吗?

So, is there any reason to use one over another like a particular case where the overrideable initialize() method would be useful?

推荐答案

为fxml文件设置控制器的两种方法之间没有功能差异。但是,就何时使用而言略有区别。

There is no functional difference between the two methods of setting a controller for an fxml file. However, in terms of when to use which there is a slight distinction.


  1. 如果您的控制器不需要任何外部对象在调用自己的 initialize()之前初始化其状态,换句话说,你的控制器类有一个 no-arg构造函数 (或者你调用 FXMLLoader setControllerFactory()并为它提供如何初始化控制器的实现)和完全可以通过 FXMLLoader 进行管理,然后你去 fx:controller 并在fxml文件中设置它。如果有这样的方法, FXMLLoader 将加载控制器并调用其 initialize()。这是链接控制器和fxml文件的默认方式。

  1. If your controller doesn't need any external objects to initialize its state before calling its own initialize(), in other words your controller class has a no-arg constructor (OR you call FXMLLoader's setControllerFactory() and provide it with implementation of how the controller should be initialized) and is fully manageable by FXMLLoader, then you go for the fx:controller and set it in the fxml file itself. FXMLLoader will load the controller and call its initialize() if there is such method. This is the default way of linking a controller and fxml file.

如果控制器的构造函数至少有1个参数或在控制器的 initialize()中,它需要访问必须在外部初始化的字段(不在控制器类中),然后手动管理控制器。您可以像创建任何其他Java类一样创建它的实例,初始化所需的内容,然后调用 setController()将控制器与fxml文件链接起来。此技术通常与自定义控制器一起使用

If you controller has a constructor with at least 1 argument or in the controller's initialize() it requires access to fields which must be initialized externally (not within the controller class), then you manually manage the controller. You create an instance of it, like with any other Java class, initialize what is required and only then call setController() to link your controller with the fxml file. This technique is typically used with custom controllers

有关详细信息,请查看此处: http://docs.oracle.com/javase/ 8 / javafx / api / javafx / fxml / doc-files / introduction_to_fxml.html#custom_components

For more details please have a look at this: http://docs.oracle.com/javase/8/javafx/api/javafx/fxml/doc-files/introduction_to_fxml.html#custom_components

这篇关于初始化控制器和FXML链接控制器之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆