Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing functionality between KeyListeners and Key Bindings

This question arose when an anonymous user downvoted an answer of mine involving KeyListeners and suggested the use of Key Bindings instead. This anonymous user informed me that the KeyListener interface was an old AWT solution and should not be used.

However, I don't know if I should trust that information completely. I have researched both on various websites, oracle included, and found nothing regarding the functionality of KeyListeners or Key Bindings. I am aware of the fact that the two perform similar tasks, but am unsure of exactly what goes on "behind the scenes", so to speak.

I'm kind of leaning towards using Key Bindings in future projects, simply because I acquired research suggesting that the KeyListener interface required that the component in question have focus while Key Bindings did not. But, I am confused. Why is this so? How are Key Bindings triggered differently than KeyListeners?

P.S. I'm pretty sure this is a rarity, but are there some circumstances where using KeyListeners is more appropriate?

like image 208
fireshadow52 Avatar asked Dec 29 '11 05:12

fireshadow52


1 Answers

How to Use Key Bindings explains the basics.

Bindings are used to map specific Actions to a specific KeyStroke.

A KeyListener is the last resort when all other abstractions won't work. Maybe you would use a KeyListener when you are listening for ANY KeyStroke. So it wouldn't be practical to create 26 bindings for all letters of the alphabet.

But again in many cases there are better API's to use. For example, instead of listening for KeyEvents on a text field you would use a DocumentListener to listen for changes to the Document.

like image 105
camickr Avatar answered Oct 06 '22 00:10

camickr