I’m working on a small Java game with a few other people and I’m a bit stuck with regards to key events. I found a code snippet online that handles keyboard input for a 2D game. What I’m confused about is how to respond to certain key events based on which part of the game you’re in. For example, if you’re at the main menu, W, A, S, and D shouldn’t work, but if you’re in the game they should.
The only solution I’ve been able to come up with so far is just to use an enum and a switch to determine which keys should be listened for. This would work but I’m not sure if there’s a better way to do it.
How do I listen for specific Java key events based on screen context?
Creating a class for each game state (‘main menu’, ‘ready screen’, ‘playing state’, etc.) would allow you to implement common KeyListener boilerplate once in a superclass and game state specific listeners and logic.
From memory the Slick library provides an API supporting this approach.