Comparing functionality between KeyListeners and Key Bindings

微笑、不失礼 提交于 2019-11-28 00:03:51

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.

I would suggest you to use KeyBindings for many reasons:

  • It actually works faster than a KeyListener.
  • KeyBinding is more developed and has much more to offer as possibilities.
  • Although you would need to use a Swing timer, it is better for games.
  • Is is settable and shareable.

It can be difficult to use it aside to a KeyListener but a KeyListener will not be able to process multiple key presses in a game.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!