【发布时间】:2019-12-07 13:14:38
【问题描述】:
我有一个项目,我需要在其中启动一个 GUI,但在另一个不是我的主线程的线程中。
-> 第一个主线程启动...
-> 如果它决定显示一个 GUI,它会启动我的 GUI。
-> 所有其他计算仍应在主线程中进行。
我的意思是,在任何情况下,我都不能在主线程中启动 gui。而且我需要能够与我的控制器进行通信(示例中没有控制器)。但是当我执行正常操作时:.. Start extends Application { .. 方法,我无法再与控制器通信,因为线程已被占用。下面的代码应该允许我做我需要做的一切,所以我希望有一种方法可以让它工作。
问题,为什么我的代码不起作用是一个异常:
线程“Thread-0”java.lang.IllegalStateException 中的异常:工具包未初始化
在我的 GuiThread 类中调用 Platform.runLater() .. 时。
提前感谢四位您的帮助。
我的主要课程:
public class Start{
private void start() {
GuiThread thread = new GuiThread();
thread.start();
System.out.println("here continues the thread, while the GUI is shown");
}
public static void main(String[] args) {
Start main = new Start();
main.start();
}
}
我的自定义线程类,我的 GUI 应该在哪里启动:
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class GuiThread extends Thread {
@Override
public void run() {
super.run();
// Here i have objects i need to have in the controller
// Then i have to start my GUI
// When calling Platform.runLater()... this error shows : Exception in thread "Thread-0" java.lang.IllegalStateException: Toolkit not initialized
Platform.runLater(() -> {
Group root;
try {
Stage stage = new Stage();
root = new Group();
Scene scene = new Scene(root);
FXMLLoader loader = new FXMLLoader(getClass().getResource("myGui.fxml"));
Node node = loader.load();
// Controller stuff
root.getChildren().add(node);
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
只是一个示例 FXML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.StackPane?>
<HBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1">
<children>
<StackPane prefHeight="150.0" prefWidth="200.0" HBox.hgrow="ALWAYS">
<children>
<Label text="left" />
</children>
</StackPane>
<StackPane prefHeight="150.0" prefWidth="200.0" HBox.hgrow="ALWAYS">
<children>
<Label text="right" />
</children>
</StackPane>
</children>
</HBox>
【问题讨论】:
-
如果
StartextendsApplication会发生什么? -
见this相关问答。
标签: java multithreading user-interface javafx