How can i use Guice in JavaFX controllers?

后端 未结 4 1264
眼角桃花
眼角桃花 2021-01-02 20:45

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

4条回答
  •  醉梦人生
    2021-01-02 21:17

    To use JavaFx with Guice :

    1. Extend javafx.application.Application & call launch method on that class from the main method. This is the application’s entry point.
    2. Instantiate dependency injection container of your choice. E.g. Google Guice or Weld.
    3. In application’s start method, instantiate FXMLLoader and set it’s controller factory to obtain controllers from the container. Ideally obtain the FXMLLoader from the container itself, using a provider. Then give it an .fxml file resource. This will create content of the newly created window.
    4. Give the Parent object instantiated in previous step to Stage object (usually called primaryStage) supplies as an argument to the start(Stage primaryStage) method.
    5. Display the primaryStage by calling it’s show() method.

    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

提交回复
热议问题