简体   繁体   中英

JavaFX can't change scene from another thread

JavaFX doesn't show a dialog box like it is supposed to when the window close is called from a thread.

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

When I run the code, I only see a black window. If I comment out the code, I see a window that says "Label".

In my actual application, I want the scene to change depending on user input to the other thread.

If I cannot call JavaFX functions from another thread, how should I do this?

Try call stage.fireEvent() on Javafx Thread using Platform.runLater(()->{}) .

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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