JavaFX 2.1: Toolkit not initialized

Found a solution. If I just create a JFXPanel from Swing EDT before invoking JavaFX Platform.runLater it works. I don't know how reliable this solution is, I might choose JFXPanel and JFrame if turns out to be unstable.

public class BootJavaFX {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JFXPanel(); // this will prepare JavaFX toolkit and environment
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        StageBuilder.create()
                                .scene(SceneBuilder.create()
                                        .width(320)
                                        .height(240)
                                        .root(LabelBuilder.create()
                                                .font(Font.font("Arial", 54))
                                                .text("JavaFX")
                                                .build())
                                        .build())
                                .onCloseRequest(new EventHandler<WindowEvent>() {
                                    @Override
                                    public void handle(WindowEvent windowEvent) {
                                        System.exit(0);
                                    }
                                })
                                .build()
                                .show();
                    }
                });
            }
        });
    }
}

The only way to work with JavaFX is to subclass Application or use JFXPanel, exactly because they prepare env and toolkit.

Blocking thread can be solved by using new Thread(...).

Although I suggest to use JFXPanel if you are using JavaFX in the same VM as Swing/AWT, you can find more details here: Is it OK to use AWT with JavaFx?


Since JavaFX 9, you can run JavaFX application without extending Application class, by calling Platform.startup():

Platform.startup(() ->
{
    // This block will be executed on JavaFX Thread
});

This method starts the JavaFX runtime.


I checked the source code and this is to initialize it

com.sun.javafx.application.PlatformImpl.startup(()->{});

and to exit it

com.sun.javafx.application.PlatformImpl.exit();