问题
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.
So, is there any reason to use one over another like a particular case where the overrideable initialize()
method would be useful?
回答1:
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.
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.If you controller has a constructor with
at least 1 argument
or in the controller'sinitialize()
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 callsetController()
to link your controller with the fxml file. 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
来源:https://stackoverflow.com/questions/30171352/difference-between-initialized-controllers-and-fxml-linked-controllers