when do you prefer one over the other?
Apply key bindings from the moment they are introduced. A KeyListener is a lower-level connection to events.
This key binding page covers many reasons why I would use them rather than KeyListener . It lists many things that are simply โinaccessibleโ to KeyListener . EG. choice:
WHEN_FOCUSEDWHEN_ANCESTOR_OF_FOCUSED_COMPONENTWHEN_IN_FOCUSED_WINDOW
The more I read a related document, the less I can understand the need to ask a question. For example:.
An alternative to key binding is to use key listeners. Key listeners have their place as a low-level interface for keyboard input, but key bindings are more suitable for responding to individual keys and, as a rule, lead to easier code storage. It is also difficult for key listeners if key binding should be active when the component has no focus. Some of the advantages of key bindings are somewhat self-documentation, consideration for the containment hierarchy, promotion of multiple code fragments ( Action objects) and makes it easy to delete, configure or share actions. In addition, they simplify changing the key to which the action is bound. Another advantage of Actions is that they have an enabled state that provides an easy way to disable an action without having to keep track of which component it is connected to.
Text components
As @Robin noted, text components also have DocumentListener and DocumentFilter , which can be added for functionality more suitable for text documents. See Text Component Functions for more information on document listeners and filters .
Andrew Thompson Mar 08 '13 at 8:54 2013-03-08 08:54
source share