簡體   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