简体   繁体   中英

Reusable controllers in FXML. One controller (slightly changed) for multiple fxml files

I would like to know whether it is possible to "reuse" the controller for another fxml after creating it. In other words, can I create a controller for fxml, modify it a bit, and then use (another instance of) it for another fxml without affecting the first one. Otherwise, I am in a way forced to copy the code from the controller, apply the changes and then use the new one.

I don't see many use cases for this, as you will obviously have different controls in different FXML files, so it's not clear how you would manage injection. If you do have a use case (eg the different FXML files just have different layouts for the same basic UI), it is possible:

Remove the fx:controller attribute from the FXML files, and set the controller manually using the following pattern:

FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/file.fxml"));
MyConfigurableController controller = new MyConfigurableController(aParam, anotherParam);
loader.setController(controller);
Parent root = loader.load();

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