线程任务完成后JavaFX显示对话

线程任务完成后JavaFX显示对话

本文介绍了线程任务完成后JavaFX显示对话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要显示对话窗口

 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();

在我的线程完成任务后

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

            });

我试过了

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();
    }

但是这个应用程序在 doSomeStuff() 完成之前没有响应

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

推荐答案

t.join() 是一个阻塞调用,所以它会阻塞 FX Application 线程,直到后台线程完成.这将防止 UI 被重新绘制,或无法响应用户输入.

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();

一种低级(即不使用 JavaFX 提供的高级 API)方法是在 FX 应用程序线程上从后台线程安排对话框的显示:

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.

这篇关于线程任务完成后JavaFX显示对话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:12