JButton 键盘快捷键
我有两个 JButton,我希望只要 JFrame
获得焦点,键盘箭头键就可以使用它们。
有人能指出我正确的方向吗?
I have two JButton
s and I would like to allow them to be used by the keyboard arrow keys whenever the JFrame
has the focus.
Can anyone point me in the right direction about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
修改自 Swing 的 Action 演示。
按钮的初始化:
操作:
Modified from Swing's Action demo.
The initialization of your button:
The action:
要拦截按键(不用担心特定组件是否处于焦点),您应该使用
InputMap
。例如,请阅读:http://java.sun。 com/docs/books/tutorial/uiswing/misc/keybinding.html
并选择
WHEN_IN_FOCUSED_WINDOW
常量。除非相关按钮只是调用单个方法,否则执行“按钮执行的操作”的最佳方法是:
To intercept the keys (without worrying if the specific component is in focus) you should use the
InputMap
. Read up on for instance:http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
And go for the
WHEN_IN_FOCUSED_WINDOW
constant.Unless the button in question simply calls a single method, the best way to do "what ever the button does" is to do:
好吧,当您说您希望允许他们使用“箭头键”时,我认为您的意思是您希望能够转移焦点。如果是这种情况,请阅读 Swing 教程中关于 如何使用焦点子系统。它举例说明了如何使用 Enter 键来实现此目的。
Well, when you say you want to allow them to use the "arrow keys", I assume you mean you want to be able to transfer focus. If this is the case then read the section from the Swing tutorial on How to Use the Focus Subsystem. It gives an example of how you can use the Enter key for this.