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

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

问题描述

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

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

每种方法的优点/缺点是什么,什么时候你应该更喜欢一种而不是另一种?

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

我阅读链接文档的次数越多,我就越不明白提出问题的必要性.例如:

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" rel="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天全站免登陆