问题
I am using JavaFX 2 with Scala.
I have the class Application extends javafx.application.Application which does things like reads app configuration, etc. Then it fires up the main window.
This main window needs to be connected to a controller called MainWindow. I can do it with fx:controller="com.foo.bar.MainWindow", however, in this case the instance of MainWindow is unable to access my application's configuration, etc.
One thing that came to my mind is to instantiate the MainWindow controller on my own inside the Application class and inject all dependencies, and then tell the main window view that the controller should be the instance I just created. However, I have no idea how to do this?
What's the preferred way to access data in controllers in JavaFX -- via some sort of dependency injection or something else?
In other words, this view FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.Scene?>
<?import javafx.scene.control.*?>
<BorderPane fx:controller="com.foo.bar.MainWindow" prefHeight="703.0" prefWidth="803.0" xmlns:fx="http://javafx.com/fxml">
...
Will automatically instantiate a com.foo.bar.MainWindow controller for me(?):
...
class MainWindow {
var app: Application = null
...
}
where I have the reference to my application, which holds information I want to access:
class Application extends javafx.application.Application {
...
// Stuff I want to access, application also fires up the first scene.
}
The problem is that how can I get a reference to the main application? How can I do dependency injection or anything equivalent?
回答1:
Guice is my preferred way of injecting controllers, all you need to use the following controller factory:
class GuiceControllerFactory implements Callback<Class<?>, Object> {
private final Injector injector;
public GuiceControllerFactory(Injector anInjector) {
injector = anInjector;
}
@Override
public Object call(Class<?> aClass) {
return injector.getInstance(aClass);
}
}
Set it on your FXMLLoader:
FXMLLoader loader = new FXMLLoader();
loader.setControllerFactory(controllerFactory);
Now Guice will create your controller. I recommend that you inject in any services your controller needs instead of passing in a reference to your application class.
来源:https://stackoverflow.com/questions/12439172/how-can-javafx-controllers-access-other-services