Search code examples
javatimeractionlistenerpane

Remove elements from pane when timer reaches 0?


I am trying to remove elements from a Pane when the timer reaches zero, more specifically a label and a text area. However, when the timer has reached 0 and I call this method I get this exception.

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = AWT-EventQueue-0

Code:

ActionListener timeListener = new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
    gameTime--;
    System.out.println(gameTime);
    if(gameTime == 0){
      endGame();
    }
  }
};

The endGame() method:

public void endGame(){
  timer.stop();
  System.out.println("Score: " + score);
view.gamePane.getChildren().removeAll(view.lblQuestion, view.tfAnswer);
}

Solution

  • You are using an AWT Action-Event. You want to remove an Item from the JavaFX-Pane. They run in different Threads.

    When you want to access JavaFX from the AWT Thread use:

    Platform.runLater(new Runnable() {
    
        @Override
        public void run() {
            //Your Access to Java FX
        }
    });
    

    But maybe you can use an JavaFX event instead of an JavaAWT event.