Scene scene = this.root.getScene(); scene.addEventHandler(KeyEvent.KEY_PRESSED, event -> gameManager.restartGame(event)); scene.removeEventHandler(KeyEvent.KEY_PRESSED, event -> gameManager.restartGame(event)); 

With this code, when you start the game, the idea is that the action should disappear when you press a button. Without adding eventHandler, the game does not respond, but it does not remove it. What could be wrong?

scene and stage are always the same

    1 answer 1

    It is not clear why to remove the handler immediately after you added it. Well, okay, God will judge you. But seriously, you need to create a handler separately, i.e. It is not a lambda to transmit it, but to create an EventHandler object directly.

     EventHandler<KeyEvent> handler = new EventHadler<>() { public void handle(KeyEvent event) { gameManager.restartGame(event); } }; scene.addEventHandler(KeyEvent.KEY_PRESSED, handler); scene.removeEventHandler(KeyEvent.KEY_PRESSED, handler); 

    I'm not 100% sure, but I think this behavior is due to the fact that when you pass handlers to a lambda, you get two different objects. Accordingly, the removal becomes problematic, since we do not know which handler should be deleted. When we have one handler object, we can uniquely identify and delete it.

    • The bottom line is that I need to check that it works fine. Those. Add and remove. Tried to do the following: EventHandler<KeyEvent> restartGameHandler = new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { restartGame(event); } }; EventHandler<KeyEvent> restartGameHandler = new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { restartGame(event); } }; Handlers themselves are called in another class. At the same time, everything crashes and shouts that something is wrong - xxxlota
    • @xxxlota Do you want to test the standard library? Be sure, if everything is done correctly (as I described), then everything will work. Otherwise it would not go into release. For a better understanding of the problem, provide a working code, or stacktarce errors, otherwise it is difficult to figure out what is wrong after all. - zolt
    • already finished with this part, figured it out, thanks - xxxlota