Gluon switch scene on custom event Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Gluon switch scene on custom event without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I try to switch the scene of a Gluon application when a custom event is fired.

When I call

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

I get the error

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


This is the listener that handles the custom event

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);
            }
        }
    });

How can this be resolved?

Answer

Any call to MobileApplication.getInstance()::switchView should happen in the JavaFX Application thread, as it basically involves changes in the scenegraph.

Roughly, you are removing the old View (which is a Node), and adding a new one (another Node):

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

And as you know, anything related to node manipulation has to be done in the JavaFX Application thread.

It seems the login event is triggered in a background thread, so all you need to do is to queue the view switch to the application thread, using 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));
        }
    }
We are here to answer your question about Gluon switch scene on custom event - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji