Wednesday, October 7, 2015

JavaFx with Spring Boot

I guess I'm not the only one trying to make JavaFx application with Spring Boot. I ended up with the best summary I could find to date (http://stackoverflow.com/questions/28804012/javafx-fxml-how-to-use-spring-di-with-nested-custom-controls) I will only put it here so I can find it again quickly :)
@SpringBootApplication
public class FxBootApplication extends Application {
    private static String[] args;

    public static void main(String[] args) {
        FxBootApplication.args = args;
        launch(args);
    }

    @Override
    public void start(final Stage primaryStage) {

        // Bootstrap Spring context here.
        ApplicationContext context = SpringApplication.run(FxBootApplication.class, args);

        // Create a Scene
        MainPaneController mainPaneController = context.getBean(MainPaneController.class);
        Scene scene = new Scene((Parent) mainPaneController.getRoot());

        // Set the scene on the primary stage
        primaryStage.setScene(scene);
        // Any other shenanigans on the primary stage...
        primaryStage.show();
    }
}
@Configuration
public class ApplicationConfiguration {

    @Bean
    public MainPaneController mainPaneController() throws IOException {
        return loadController(MainPaneController.VIEW);
    }

    private  T loadController(String url) throws IOException {
        try (InputStream fxmlStream = getClass().getResourceAsStream(url)) {
            FXMLLoader loader = new FXMLLoader();
            loader.load(fxmlStream);
            return loader.getController();
        }
    }
}
public class MainPaneController {
    public static final String VIEW = "/MainPanel.fxml";

    @FXML
    private Node root;
   
    @PostConstruct
    public void init() {}

    public Node getRoot() {
        return root;
    }
}