我目前正在尝试使用Stage
对象在后台线程中创建一个Task<Stage>
,这不起作用,因为Task
永远不会完成。
这是我的代码:
Task<Stage> myTask = new Task<Stage>() {
@Override
protected Stage call() throws Exception {
Stage stage = new Stage();
return stage;
}
};
myTask.setOnSucceeded(e -> {
System.out.println("done :D");
});
myTask.setOnFailed(e -> {
System.out.println("oh no");
myTask.getException().printStackTrace();
});
new Thread(myTask).start();
上面的方法打印oh no
并显示以下异常消息:
java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-5
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(Unknown Source)
at javafx.stage.Stage.<init>(Unknown Source)
at javafx.stage.Stage.<init>(Unknown Source)
at controller.ManageWebsiteTestsWindowController$OpenButton$1.call(ManageWebsiteTestsWindowController.java:77)
at controller.ManageWebsiteTestsWindowController$OpenButton$1.call(ManageWebsiteTestsWindowController.java:1)
at javafx.concurrent.Task$TaskCallable.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
当我使用相同的代码创建例如Label
,它完美无缺:
Task<Label> myTask = new Task<Label>() {
@Override
protected Label call() throws Exception {
Label label = new Label("Hello World");
return label;
}
};
myTask.setOnSucceeded(e -> {
System.out.println("done :D");
});
myTask.setOnFailed(e -> {
System.out.println("oh no");
myTask.getException().printStackTrace();
});
new Thread(myTask).start();
我做错了什么?
一些背景信息:我正在尝试创建一个扩展Popout
的{{1}}对象。