"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Create Multiple JavaFX Windows without Recalling launch()?

How to Create Multiple JavaFX Windows without Recalling launch()?

Published on 2024-11-09
Browse:237

How to Create Multiple JavaFX Windows without Recalling launch()?

How to Call launch() More Than Once in Java

The JavaFX application launch method, launch(), is designed to be called only once per application. Attempting to call launch() more than once results in an "IllegalStateException" error.

Solution: Wrap Subsequent Window Creation in Platform.runLater()

Instead of calling launch() multiple times, consider the following approach:

  1. Call launch() once to initialize the JavaFX runtime and create the main window.
  2. Keep the JavaFX runtime running in the background using Platform.setImplicitExit(false). This prevents JavaFX from shutting down automatically when the main window is closed.
  3. When you need to display a new window, wrap its creation and display in a Platform.runLater() block. This ensures that JavaFX operations are executed on the application thread.

Example Code:

public class Wumpus extends Application {
    private static final Insets SAFETY_ZONE = new Insets(10);
    private Label cowerInFear = new Label();
    private Stage mainStage;

    @Override
    public void start(final Stage stage) {
        mainStage = stage;
        mainStage.setAlwaysOnTop(true);
        Platform.setImplicitExit(false);
        cowerInFear.setPadding(SAFETY_ZONE);

        cowerInFear.setOnMouseClicked(event -> Platform.exit());
        stage.setScene(new Scene(cowerInFear));
    }

    public static void main(String[] args) {
        launch(args);

        // Another window can be created here by wrapping its creation
        // and display in a Platform.runLater() block.
        Platform.runLater(() -> {
            Stage newStage = new Stage();
            newStage.setScene(new Scene(new Label("Another Window")));
            newStage.show();
        });
    }
}

Note:

  • The Wumpus class above demonstrates the approach with a custom JavaFX application.
  • For use with Swing components, a JFXPanel can be used instead of an Application.
  • Calling Platform.exit() will terminate the JavaFX runtime, so it is important to call this method when all JavaFX operations are complete.
Release Statement This article is reprinted at: 1729695676 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3