Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...