People here keep suggesting to me to use Key Binding instead of KeyListener in Java 2D games.

What are the advantages and disadvantages of each one? Is Key Bindings really better for 2D games?


KeyListener is a much lower level API which requires the component that it is registered to be focused AND have keyboard focus. This can cause issues when you have other components within your game that may grab keyboard focus, for example.

KeyListener is generally more difficult to maintain and extend or change, as typically, all the key events are channelled through a single listener, so ALL the game controls originate from this single position.

(Now imagine you want to add other controls, such as buttons or even joystick or controllers to mix - you suddenly have any number of input hubs you need to consider, keep up to date and in sync :P)

The Key Bindings API has been designed to provide re-usable Actions which can be used in a variety of different parts of the Swing API, while this makes desktop application development easier, it can also make it easier when developing games...

Apart from the fact that you now gain control over the focus level that the events are generated, you also gain the flexibility to defining configurable key's which can be mapped to different actions

For example...

You define an Up Action, which moves you character up. This is divorced from any event. That means, the Action does not care how it is triggered, only what it should do when it is triggered.

You are now free to define the keystroke which would trigger this action. The great part about this, is suddenly have the ability to provide customisation to the user, so they can actually define the key stroke they want for the action - for example, without having to design some kind of key mapping system of your own.

It also means that you can use the same Action (and even the same instance) in a variety of different ways. For example, you can bind the Action to a key stroke and add it to button and if you're brave enough to try, even bind it another input device (like a joystick or controller)...but you'd need to build the API yourself to achieve it, but it means you suddenly have a single API concept for all your user input, for example...