Java:如何使用加速器创建粘贴菜单项?
当我创建一个包含粘贴操作的 JMenuBar 并为其分配加速器 (Control - V) 时,我为 JMenuItem 编写粘贴操作。并且我使用加速器,我的代码将被执行,并且 Swing 预编程的粘贴操作将被执行,因此我认为文本将被粘贴两次。
我没有测试它,但是,这看起来很合乎逻辑,这就是问题所在。
谢谢
When I create a JMenuBar with a Paste action in it and assign an accelerator to it (Control - V) and I write the paste action for the JMenuItem. AND I use the accelerator, my code will be executed and the Swing preprogrammed Paste action will be executed, so the text will be pasted twice, I think.
I didn't test it but, it looks very logical that this would be the problem.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Swing 通过使用键绑定来工作。因此,根据找到的键绑定,仅调用一个操作。所以你不会把文本粘贴两次。
您可能会调用不同的操作,具体取决于哪个组件具有焦点以及操作的调用方式。
例如,如果焦点位于文本组件上,那么我猜测将使用默认的粘贴操作。
如果单击菜单项,则会调用添加到菜单项的操作。
如果您在焦点不在文本字段上时调用 Control+V,那么我猜会调用绑定到菜单项的操作,因为加速器使用“焦点窗口”(或任何名称)InputMap。
如果您使用 EditorKit 提供的默认操作,则不会有问题:
Swing works by using Key Bindings. So only one action is invoked depending on which key binding is found. So you wound not get the text pasted twice.
You may have a different Action invoked depending on which component has focus and on how the Action was invoked.
For example, if focus is on the text component, then I would guess that the default Paste action will be used.
If you click on the menu item, then the action you added to the menu item would be invoked.
If you invoke Control+V when focus in not on a text field, then I would guess the Action bound to the menu item would be invoked because accelerators use the "in focus window" (or whatever its called) InputMap.
If you are using the default Actions provided by the EditorKit you will not have a problem: