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;
    }
}

5 comments:

  1. Thank you, thank you, thank you!

    ReplyDelete
  2. Hello, is it really working for you? Because for me it crashes while doing "mainPaneController.getRoot()" because root is null. Could you please help me with that? Code is the same as yours, spring boot version 1.3.2

    ReplyDelete
  3. I was able to fix the getRoot() returning null with @FXML on it.

    ReplyDelete
  4. Perhaps someone wants to try out my JavaFX support library and improve it with me:
    https://github.com/roskenet/springboot-javafx-support

    ReplyDelete