比较KeyListener和Key Bindings之间的功能 [英] Comparing functionality between KeyListeners and Key Bindings

查看:60
本文介绍了比较KeyListener和Key Bindings之间的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个匿名用户不赞成我的涉及KeyListeners的答案并建议使用Key Bindings时,出现了这个问题.这位匿名用户告诉我,KeyListener接口是一个旧的AWT解决方案,不应使用.

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.

但是,我不知道我是否应该完全信任那些信息.我已经在包括oracle在内的各种网站上进行了研究,但没有发现关于KeyListeners或Key Bindings的功能.我知道两个人执行相似的任务这一事实,但是可以肯定地说,幕后"到底发生了什么.

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.

我倾向于在将来的项目中使用键绑定,因为我获得的研究表明,KeyListener接口要求有问题的组件具有焦点,而键绑定则没有.但是,我很困惑.为什么会这样呢?按键绑定与键侦听器的触发方式有何不同?

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?

PS .我很确定这很罕见,但是在某些情况下使用KeyListeners更合适吗?

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

推荐答案

如何使用键绑定解释了基础知识.

绑定用于将特定的动作映射到特定的KeyStroke.

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

当所有其他抽象都不起作用时,KeyListener是最后的选择.在侦听任何KeyStroke时,也许会使用KeyListener.因此为字母表的所有字母创建26个绑定是不切实际的.

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.

但是在许多情况下,还是可以使用更好的API.例如,可以使用DocumentListener侦听对文档所做的更改,而不是在文本字段上侦听KeyEvent.

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.

这篇关于比较KeyListener和Key Bindings之间的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆