Java中的键绑定与键侦听器
作者:互联网
我注意到在Java / Swing中,似乎至少有两种不同的方法来处理关键事件:
每个人的优点/缺点是什么,何时你更喜欢一个而不是另一个?
解决方法:
when should you prefer one rather than the other?
因为它们被引入所以更喜欢Key Bindings. KeyListener是与事件的较低级别连接.
key bindings的那个页面涵盖了我倾向于使用它们而不是KeyListener的很多原因.它列出了许多对KeyListener来说简单“不可用”的东西.例如.选择:
> WHEN_FOCUSED
> WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
> WHEN_IN_FOCUSED_WINDOW
我阅读链接文档越多,我就越不能理解提出问题的必要性.例如.:
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 ofActions
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
可以添加更适合文本文档的功能.有关文件listeners& ;;的更多信息,请参见Text Component Features. filters.
标签:keylistener,key-events,java,swing,key-bindings 来源: https://codeday.me/bug/20190915/1805513.html