Key bindings vs. key listeners in Java

mikera picture mikera · Mar 8, 2013 · Viewed 7.6k times · Source

I note that in Java / Swing there seem to be at least two different ways of handling key events:

What are the advantages / disadvantages of each, and when should you prefer one rather than the other?

Answer

Andrew Thompson picture Andrew Thompson · Mar 8, 2013

when should you prefer one rather than the other?

Prefer Key Bindings since they were introduced. A KeyListener is a lower level connection with events.

That page for the key bindings covers a lot of the reasons I would tend to use them rather than a KeyListener. It lists many things which are simply 'not available' to a KeyListener. E.G. choices of:

  • WHEN_FOCUSED
  • WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
  • WHEN_IN_FOCUSED_WINDOW

The more I read the linked document, the less I can understand the need to ask the question. E.G.:

An alternative to key bindings is using key listeners. Key listeners have their place as a low-level interface to keyboard input, but for responding to individual keys key bindings are more appropriate and tend to result in more easily maintained code. Key listeners are also difficult if the key binding is to be active when the component doesn't have focus. Some of the advantages of key bindings are they're somewhat self documenting, take the containment hierarchy into account, encourage reusable chunks of code (Action objects), and allow actions to be easily removed, customized, or shared. Also, they make it easy to change the key to which an action is bound. Another advantage of Actions is that they have an enabled state which provides an easy way to disable the action without having to track which component it is attached to.

Text components

As noted by @Robin, text components also have DocumentListener & DocumentFilter which can be added for functionality more suited to text documents. See Text Component Features for more information on document listeners & filters.