Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

java - JavaFX show dialogue after thread task is completed

I need to show dialogue window

 Stage dialog = new Stage();
            dialog.initStyle(StageStyle.UTILITY);
            Scene scene = new Scene(new Group(new Text(25, 25, "All is done!")));
            dialog.setScene(scene);
            dialog.showAndWait();   

after my thread completes the task

Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                   doSomeStuff();
                }

            });

I've tried

Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                doSomeStuff();
            }

        });
        t.start();
        t.join();
        Stage dialog = new Stage();
        dialog.initStyle(StageStyle.UTILITY);
        Scene scene = new Scene(new Group(new Text(25, 25, "All is done!")));
        dialog.setScene(scene);
        dialog.showAndWait();
    }

but this app is not responsing until doSomeStuff() is finished

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

t.join() is a blocking call, so it will block the FX Application thread until the background thread completes. This will prevent the UI from being repainted, or from responding to user input.

The easiest way to do what you want is to use a Task:

Task<Void> task = new Task<Void>() {
    @Override
    public Void call() throws Exception {
        doSomeStuff();
        return null ;
    }
};
task.setOnSucceeded(e -> {
    Stage dialog = new Stage();
    dialog.initStyle(StageStyle.UTILITY);
    Scene scene = new Scene(new Group(new Text(25, 25, "All is done!")));
    dialog.setScene(scene);
    dialog.showAndWait();
});
new Thread(task).start();

A low-level (i.e. without using the high-level API JavaFX provides) approach is to schedule the display of the dialog on the FX Application thread, from the background thread:

Thread t = new Thread(() -> {
    doSomeStuff();
    Platform.runLater(() -> {
        Stage dialog = new Stage();
        dialog.initStyle(StageStyle.UTILITY);
        Scene scene = new Scene(new Group(new Text(25, 25, "All is done!")));
        dialog.setScene(scene);
        dialog.showAndWait();
    });
});
t.start();

I strongly recommend using the first approach.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...