我们正在开发一个客户端-服务器应用程序,它必须同时使用 GUI 和 CLI。 我们对 CLI 没有任何问题,但我们在使用 JavaFX 实现它时遇到了困难:
我们的服务器向客户端发送一些对象(通过套接字),这些对象必须被处理。
这是我们的 SocketServerListener(和编写器):
public class SockeServerListener extends Thread implements ServerListener{
private CliController controller;
private ObjectInputStream in;
private ObjectOutputStream out;
public SocketServerListener(Socket server, CliController controller) throws UnknownHostException, IOException {
this.controller = controller;
this.out = new ObjectOutputStream(server.getOutputStream());
this.in = new ObjectInputStream(server.getInputStream());
}
public void publishMessage(String message) throws IOException, RemoteException {
out.writeObject(message);
out.flush();
}
public void run() {
try {
while (true) {
Dialogue dialogue = (Dialogue) in.readObject();
controller.parseDialogue(dialogue);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
SocketServerListener 由 Controller 实例化,该 Controller 执行“执行”接收到的对象,更新界面(Cli/GUI)
public void parseDialogue(Dialogue dialog) {
dialog.execute(view); //view is an interface extended by both the Cli and GUI
this.canWrite = true;
}
正如我所说,这在 CLI 中运行得很好,但在 JavaFX 中会抛出异常
Exception in thread "Thread-7" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-7
我们尝试使用用于生成所有 GUI 的类作为 Controller ,但没有任何(积极的)结果。 我们如何实例化一个线程,以便它可以与 JavaFX 一起工作并调用显示我们需要的屏幕的方法?
谢谢
最佳答案
Not on FX application thread
为您提供问题的原因。
根据 Node 的 Javadoc类:
Node objects may be constructed and modified on any thread as long they are not yet attached to a Scene in a Window that is showing. An application must attach nodes to such a Scene or modify them on the JavaFX Application Thread.
使用Platform.runLater在 FX 应用程序线程上执行代码并查看 javafx.concurrent进一步实用程序类的包。
关于JavaFx 和套接字监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37764061/