Thread.sleep之后无法启动Java GUI

时间:2018-08-13 09:59:00

标签: java multithreading javafx

我试图在满足特定条件时(但在满足条件时)弹出一个窗口。窗口没有打开。我正在使用Thread.sleep

代码:

public void grow() {
    Thread thread = new Thread(() -> {
        try {
            Thread.sleep(this.harvestTime);
            if(water >= waterNeeded && fertelizer >= fertelizerNeeded) {
                this.harvest = true;
                AlertBox.display("CROP ALERT","A SEED HAS FINISHED GROWING");
                Thread.sleep(60000);
                if(harvest == true) {
                    withered = true;
                    harvest = false;
                    AlertBox.display("ALERT", "FAILED TO HARVEST A CROP. IT BECAME WITHERED!");
                }
            }
            else {
                this.withered = true;
            }
        } catch (Exception e) {
        }
    });
    thread.start();
}

1 个答案:

答案 0 :(得分:0)

Java FX方法仅在Java FX线程中有效。您不能也不应使用后台线程中的Java FX组件/方法。

如果您需要显示来自后台线程的通知,请使用:

Platform.runLater(new Runnable() {
    @Override public void run() {
        bar.setProgress(counter / 1000000.0);
    }
});

在这种情况下,Runnable将被添加到Java FX事件队列中,并将在Java FX线程中进行处理。