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

后端 未结 1 719
别那么骄傲
别那么骄傲 2020-12-01 16:53

The application reacts on actions which occur on gamepad. When button is pressed something happens on UI. But I ran at the issue with app hangs up or \"java.lang.IllegalStat

相关标签:
1条回答
  • 2020-12-01 17:20

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题