繁体   English   中英

JavaFX 无法从另一个线程更改场景

[英]JavaFX can't change scene from another thread

JavaFX 不会像从线程调用 window 关闭时那样显示对话框。

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application
{

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

    @Override
    public void start(Stage stage) throws Exception
    {

        Task<Void> task = new Task<Void>()
        {
            @Override
            public Void call() {
                VBox vBox = new VBox();
                vBox.getChildren().add(new Label("Label"));
                stage.setScene(new Scene(vBox));
                return null;
            }
        };
        new Thread(task).start();
        stage.show();
//      VBox vBox = new VBox();
//      vBox.getChildren().add(new Label("Label"));
//      stage.setScene(new Scene(vBox));
    }
}

当我运行代码时,我只看到一个黑色的 window。 如果我注释掉代码,我会看到一个 window,上面写着“标签”。

在我的实际应用程序中,我希望根据用户对另一个线程的输入来改变场景。

如果我不能从另一个线程调用 JavaFX 函数,我应该怎么做?

尝试使用Platform.runLater(()->{})在 Javafx 线程上调用stage.fireEvent() ) 。

例子:

public Void call() {
    try {
        Thread.sleep(2000);
    }
    catch (InterruptedException e) {
    }
    System.out.println("Sending close request two:");
    Platform.runLater(() -> stage.fireEvent(new WindowEvent(stage, WindowEvent.WINDOW_CLOSE_REQUEST)));
    System.out.println("Sent close request two:");
    return null;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM