Java Swing L&F 本机键盘快捷键
如何在 Java Swing 应用程序中利用标准操作系统键盘快捷键?我了解了如何向我的应用程序添加 javax.swing.JToolbar
或菜单栏,但它似乎并未绑定到事实上的标准键盘快捷键(例如Ctrl+S 保存)。
How do I leverage standard operating system keyboard shortcuts in a Java Swing application? I see how to add a javax.swing.JToolbar
or a menu bar to my application, but it doesn't appear to be bound to de facto standard keyboard shortcuts (like Ctrl+S for Save).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
Toolkit.getDefaultToolkit.getMenuShortcutKeyMask()
获取每个平台的正确修饰键(Ctrl, 命令等),但我不知道有什么方法可以找出操作的“标准”快捷方式,而无需自己定义它们。不过,在本地化方面更出色的东西(例如 SWT)可能更擅长这种事情。
You can use
Toolkit.getDefaultToolkit.getMenuShortcutKeyMask()
to get the correct modifier key per-platform (Ctrl, Command, etc.), but I'm not aware of any way to find out what the "standard" shortcuts for an action are, without defining them yourself.Something that excels a little bit more at being native, like SWT, might be better at this kind of thing, though.
根据其他人的答案,我想我应该分享我在自己的应用程序中所做的事情...
首先,我有一个类变量,它的声明和初始化如下:
接下来,在同一个类中,我有这个方法:
现在,创建一个新菜单所需要做的就是编写如下内容:
正如您可能想象的那样,这是一种非常方便的清理代码的方法,我正在设置一个包含数十个项目的菜单!我希望这对某人有帮助。 (我没有走操作路线,因为它需要我为每个操作设置一个新类......这似乎是一个令人恼火的限制,必须绕过。我很确定这段代码比那段代码短会的。)
Building off of other people's answers, I thought I'd share what I did in my own app...
First, I have a class variable which is declared and initialized like this:
Next, in the same class, I have this method:
Now, all that I have to do to create a new menu is write something like:
As you might imagine, it's a really handy method for cleaning up code where I'm setting up a menu with dozens of items! I hope that helps someone. (I didn't go the Action route because it would require me to set up a new class for each action... that seemed like an irritating limitation to have to get around. I'm pretty sure this code is shorter than that code would be.)
阅读有关如何使用操作的 Swing 教程。
Action 基本上是一个具有更多属性的 ActionListener。您可以定义操作的文本、助记符和加速器。然后,您可以使用相同的操作来创建添加到工具栏的 JButton 或添加到菜单的 JMenuItem。
Read the Swing tutorial on How to Use Actions.
An Action is basically an ActionListener with a few more properties. You can define the text, mnemonic and accelerators for the Action. Then you can use the same Action to create a JButton which you add to a toolbar or a JMenuItem which you add to a menu.
您应该手动将键盘快捷键绑定到所需的菜单项。例如,在 JMenuItem 上使用 setAccelerator() 方法。
You should manually bind your keyboard shortcut to the desired menu entry. For example using the setAccelerator() method on JMenuItem.