初始化控制器和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.
-
如果您的控制器不需要任何外部对象在调用自己的
initialize()
之前初始化其状态,换句话说,你的控制器类有一个no-arg构造函数
(或者你调用FXMLLoader
的setControllerFactory()
并为它提供如何初始化控制器的实现)和完全可以通过FXMLLoader
进行管理,然后你去fx:controller
并在fxml文件中设置它。如果有这样的方法,FXMLLoader
将加载控制器并调用其initialize()
。这是链接控制器和fxml文件的默认方式。
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 ano-arg constructor
(OR you callFXMLLoader
'ssetControllerFactory()
and provide it with implementation of how the controller should be initialized) and is fully manageable byFXMLLoader
, then you go for thefx:controller
and set it in the fxml file itself.FXMLLoader
will load the controller and call itsinitialize()
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