我们正在开发一个客户端服务器应用程序,它必须同时使用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由控制器实例化,控制器是执行接收对象的执行者,更新接口(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的类作为控制器,但没有任何(正)结果。我们如何实例化一个线程,以便它能够与JavaFX一起工作,并调用显示我们需要的屏幕的方法?
谢谢
发布于 2016-06-11 13:29:03
据推测,对controller.parseDialogue(dialogue);的调用正在更新UI。您只能在FX应用程序线程上这样做。您可以使用Platform.runLater()在FX应用程序线程上调度可运行的执行
Platform.runLater( () -> controller.parseDialogue(dialogue) );请注意,如果您不知道在FX工具箱已经启动的上下文中执行这段代码,则应该在控制器中调用Platform.runLater(...)。
public class NonGuiController implements CliController {
@Override
public void parseDialog(Dialogue dialogue) {
// regular code here...
}
}和
public class GuiController implements CliController {
@Override
public void parseDialogue(Dialogue dialogue) {
// some preliminary work (still on background thread here) if necessary...
Platform.runLater(() -> {
// code that updates UI here...
});
}
}并恢复到套接字侦听器类中的原始代码。
发布于 2016-06-11 13:29:21
不在FX应用程序线程上
告诉你问题的原因。
根据节点类的Javadoc:
节点对象可以在任何线程上构造和修改,只要它们尚未连接到正在显示的窗口中的场景。应用程序必须将节点附加到这样的场景,或者在JavaFX应用程序线程上修改它们。
使用Platform.runLater在FX应用程序线程上执行代码,并查看进一步实用程序类的javafx.concurrent包。
https://stackoverflow.com/questions/37764061
复制相似问题