Difference between initialized controllers and FXML linked controllers?

五迷三道 提交于 2019-12-01 06:53:57

问题


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.

  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



来源:https://stackoverflow.com/questions/30171352/difference-between-initialized-controllers-and-fxml-linked-controllers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!