简体   繁体   中英

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.

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

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. 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.

  2. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM