[英]Difference between initialized controllers and FXML linked controllers?
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. 直到最近我才知道你可以在FXML
文件中设置带有fx:controller
,所以我依靠FXMLLoader's
setController
来管理链接。
So, is there any reason to use one over another like a particular case where the overrideable initialize()
method would be useful? 那么,是否有任何理由使用一个而不是像可overrideable initialize()
方法有用的特定情况?
There is no functional difference between the two methods of setting a controller for an fxml file. 为fxml文件设置控制器的两种方法之间没有功能差异。 However, in terms of when to use which there is a slight distinction. 但是,就何时使用而言略有区别。
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. 如果你的控制器在调用它自己的initialize()
之前不需要任何外部对象来初始化它的状态,换句话说你的控制器类有一个no-arg constructor
(或者你调用FXMLLoader
的setControllerFactory()
并为它提供实现如何控制器应该被初始化并且FXMLLoader
完全可以管理,然后你去fx:controller
并将它设置在fxml文件本身。 FXMLLoader
will load the controller and call its initialize()
if there is such method. 如果有这样的方法, FXMLLoader
将加载控制器并调用其initialize()
。 This is the default way of linking a controller and fxml file. 这是链接控制器和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. 如果控制器的构造函数at least 1 argument
或者在控制器的initialize()
则需要访问必须在外部初始化的字段(不在控制器类中),然后手动管理控制器。 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. 您可以像创建任何其他Java类一样创建它的实例,初始化所需的内容,然后调用setController()
将控制器与fxml文件链接。 This technique is typically used with custom controllers 此技术通常与自定义控制器一起使用
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 有关详细信息,请查看此内容: http : //docs.oracle.com/javase/8/javafx/api/javafx/fxml/doc-files/introduction_to_fxml.html#custom_components
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.