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