Gluon 在自定义事件上切换场景

Gluon switch scene on custom event

我尝试在触发自定义事件时切换 Gluon 应用程序的场景。

当我打电话时

MobileApplication.getInstance().switchView(SECONDARY_VIEW);"

我收到错误

Exception in thread "Thread-6" java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = Thread-6


这是处理自定义事件的侦听器

ParallelServerInterface.setLoginResponseListener(new LoginResponseListener() {
        @Override
        public void loginResponseReceived(LoginResponse loginResponse) {
            Map<String, String> source = (Map<String, String>) loginResponse.getSource();
            boolean status = source.get("status").equals("true");

            if (status) {
                MobileApplication.getInstance().switchView(SECONDARY_VIEW);
            }
        }
    });

如何解决?

任何对 MobileApplication.getInstance()::switchView 的调用都应该发生在 JavaFX 应用程序线程中,因为它基本上涉及场景图中的更改。

粗略地说,您要删除旧视图(一个 Node),并添加一个新视图(另一个 Node):

glassPane.getChildren().remove(oldNode);
glassPane.getChildren().add(newNode);

如您所知,任何与节点操作相关的事情都必须在 JavaFX 应用程序线程中完成。

似乎登录事件是在后台线程中触发的,所以您需要做的就是将视图切换排队到应用程序线程,使用 Platform.runLater:

    @Override
    public void loginResponseReceived(LoginResponse loginResponse) {
        Map<String, String> source = (Map<String, String>) loginResponse.getSource();
        boolean status = source.get("status").equals("true");

        if (status) {
            // switch view has to be done in the JavaFX Application thread:
            Platform.runLater(() ->
                MobileApplication.getInstance().switchView(SECONDARY_VIEW));
        }
    }