JavaFX 应用线程

JavaFX Application Thread

我有一个关于 JavaFX 的问题。我的程序使用客户端-服务器模型。当在客户端(rmi-callback)上通过服务器调用方法时发生错误。从客户端程序调用方法 newGame 时收到以下错误代码:

Exception in thread "JavaFX Application Thread" java.lang.IllegalStateException: Not on FX application thread; currentThread = RMI TCP Connection(1)-127.0.0.1
    at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:236)
    at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:423)
    ...

客户端程序代码:

public class LoginCLIENT extends Application implements Serializable {

    @Override
    public void start(Stage primaryStage) {
        Registry registry;
        try {
            registry = LocateRegistry.getRegistry(4242);
            server = (FPServerInterface)registry.lookup("ServerInterface");

        } catch (RemoteException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NotBoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //not important code

    }

    public static void main(String[] args) {
        launch(args);
    }

    public void newGame(SessionInterface Opponent) throws RemoteException{
        alert = new Alert(AlertType.CONFIRMATION, "Yes or No"); 
        Optional<ButtonType>result = alert.showAndWait(); 
        if (result.isPresent() && result.get() == ButtonType.OK){
            System.out.println("Lets play!!!");
        }
    }

这可能与 How to avoid Not on FX application thread; currentThread = JavaFX Application Thread error? 重复。我没有足够的声誉来留下评论。

问题是您从不是 FX 线程的线程调用 newGame() 方法。只需将调用包装在 Platform.runLater(Runnable).

示例:

... your code
final SessionInterface opponent = ...wherever you get the opponent from
Platform.runLater(() -> newGame(opponent));