How to launch applications from java and keep launched application on top current application

Viewed 57

I have a javaFX application which is basically a portal. It contains buttons which can be used to launch various other applications.

A simplified testable version would be:

public class PortalApplication extends Application {

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

    @Override
    public void start(Stage primaryStage) {
        FlowPane root = new FlowPane();
        primaryStage.setScene(new Scene(root));
        primaryStage.setMaximized(true);
        primaryStage.show();

        root.getChildren().add(createButton("Launch 'Notepad'", "notepad"));
        root.getChildren().add(createButton("Launch 'My App'", "java -jar app1.jar"));
        //..

    }

    private Button createButton(String title, String command) {
        Button button = new Button(title);
        button.setOnAction(event -> {
            button.setDisable(true);
            new Thread(() -> {
                try {
                    Thread.sleep(1000); //simulated delay
                    Runtime.getRuntime().exec(command);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        });
        return button;
    }
}

Problem: Sometimes the users launch an application then click again in the portal while the application is loading or running, causing the newly started application to lose focus and go behind the portal application. Most users don't realize this and think the launched application didn't start.

How can I launch the applications so that they always stay on top of my portal application?

I think a solution would be that every time the portal application gets focused, I could programmatically transfer focus to the launched application if it exists, but I didn't manage to find a way to do it

0 Answers
Related