I have a JavaFX application where I would like to introduce Guice because my Code is full of factorys right now, only for the purpose of testing.
I have one use case
To use JavaFx with Guice :
Code Example MyApp.java
public class MyApp extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
Injector injector = Guice.createInjector(new GuiceModule());
//The FXMLLoader is instantiated the way Google Guice offers - the FXMLLoader instance
// is built in a separated Provider called FXMLLoaderProvider.
FXMLLoader fxmlLoader = injector.getInstance(FXMLLoader.class);
try (InputStream fxmlInputStream = ClassLoader.getSystemResourceAsStream("fxml\\login.fxml")) {
Parent parent = fxmlLoader.load(fxmlInputStream);
primaryStage.setScene(new Scene(parent));
primaryStage.setTitle("Access mini Stock App v1.1");
primaryStage.show();
primaryStage.setOnCloseRequest(e -> {
System.exit(0);
});
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
launch();
}
}
Then FXMLLoaderProvider.java
public class FXMLLoaderProvider implements Provider {
@Inject Injector injector;
@Override
public FXMLLoader get() {
FXMLLoader loader = new FXMLLoader();
loader.setControllerFactory(p -> {
return injector.getInstance(p);
});
return loader;
}
}
Thanks to mr. Pavel Pscheidl who provided us with this smart code at Integrating JavaFX 8 with Guice