Home > Enterprise >  How to dynamically create stage from another class in JavaFX
How to dynamically create stage from another class in JavaFX

Time:10-13

Supposedly I have an extended application class to launch from another class

public class BasicApp extends Application {
    public static CountDownLatch instanceLatch = new CountDownLatch(1);
    public static BasicApp instance;

    public synchronized static BasicApp getInstance() {
        if(instance == null) {
            try {
                new Thread(() -> Application.launch(BasicApp.class)).start();
                instanceLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return instance;
    }

    public BasicApp () {
        instance = this;
        instanceLatch.countDown();
    }
.
.
.

And I want to create multiple instances of the same stage from another class, so I might create a list of stage

    private static List<Stage> stages;

    @Override
    public void start(Stage primaryStage) throws Exception {
        for (Stage st : stages) {
            st.show();
        }
    }
.
.
.

so I define a static method to instantiate the stage from another class

    public static Stage createStage(String data) {
        Stage stage = new Stage();
        Scene scene = new Scene(new Label(data));
        stage.setScene(scene);

        stages.add(stage);

        return stage;
    }
}

However, when I tried to launch the class and create the stage,

public class MainClass {
    public static void main (String[] args) {
        BasicApp app = getInstance();
        app.createStage("Test");
    }
}

It threw an exception that says Stage cannot be created outside the FX Application thread. java.lang.IllegalStateException: Not on FX application thread;

The app instance has no problem, yet, How do I achieve to create the instance of the same stage without getting this error?

CodePudding user response:

You can use Platform.runLater() to execute code on the FX application thread.

public class MainClass {
    public static void main (String[] args) {
        BasicApp app = getInstance();
        Platform.runLater(() -> createStage("Test"));
    }
}
  • Related