Java中的键绑定与键侦听器 [英] Key bindings vs. key listeners in Java

查看:169
本文介绍了Java中的键绑定与键侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在Java / Swing中似乎至少有两种处理关键事件的方式:

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

  • Key Bindings
  • Key Listeners

每个的优点/缺点是什么,何时你更喜欢一个而不是另一个?

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

推荐答案


你应该什么时候而不是另一个?

when should you prefer one rather than the other?

首选密钥绑定因为它们被引入。 KeyListener 是与事件的较低级别连接。

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

键绑定涵盖了我倾向于使用它们的很多原因,而不是 KeyListener 。它列出了许多对 KeyListener 简单不可用的内容。例如。选择:

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

  • WHEN_FOCUSED
  • WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
  • WHEN_IN_FOCUSED_WINDOW

我阅读链接文档越多,我就越不能理解提出问题的必要性。 E.G。:

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


键绑定的替代方法是使用键侦听器。键侦听器可以作为键盘输入的低级接口,但是对于单个键的响应,键绑定更合适,并且往往会导致更容易维护的代码。如果在组件没有焦点时要激活键绑定,则键侦听器也很困难。密钥绑定的一些优点是它们有点自我记录,考虑包含层次结构,鼓励可重用的代码块( Action 对象),并允许操作轻松删除,自定义或共享。此外,它们可以轻松更改操作绑定的键。 Actions 的另一个优点是它们具有一个启用状态,它提供了一种简单的方法来禁用该操作,而无需跟踪它所连接的组件。

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.



文本组件



如@Robin所述,文本组件也有 DocumentListener & DocumentFilter 可以添加更适合文本文档的功能。有关文档文本组件功能。 http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#doclisteners =noreferrer>听众& 过滤器

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.

这篇关于Java中的键绑定与键侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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