App hangs up or “Not on FX application thread” occurs during app activity

Explanation

In the first scenario, when you are using

Task task = new Task<Void>() {
  @Override
  protected Void call() throws Exception {
      initStubGamepad();
      return null;
  }
}

Inside initStubGamepad(), which is running on a Task, you are trying to update the UI components inside pressBtn() and releaseBtn() methods, which is why you are facing a

java.lang.IllegalStateException: Not on FX application thread

because all the UI updates must occur on the JavaFX thread

In the second scenario, when you are using

Platform.runLater(new Runnable() {
    @Override
    public void run() {
        initStubGamepad();
    }
});

the UI doesnt appear, because you have an infinite loop inside the initStubGamepad(), which puts the JavaFX application thread run on an infinite loop

Solution

By the time you have reach here, you must have already found the solution. In case you haven’t, try try to put the update the Javafx components on the UI thread. So, instead of calling initStubGamepad() inside Platform.runLater, try calling pressBtn() and releaseBtn() inside it.

Try using

while (true) {
   if (rnd.nextInt(30) == 3) {
      Platform.runLater(() -> pressBtn());            
   } else if (rnd.nextInt(30) == 7) {
       Platform.runLater(() -> releaseBtn());            
   }
}

or you may also use

public void pressBtn() {
    if(!isXPressed) {
        Platform.runLater(() -> iv1.setVisible(true));
        isXPressed = true;
    }
}

Leave a Comment