java JButton 的热键/快捷方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15725237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hotkey/Shortcut for JButton
提问by Lord Rixuel
I have the following code of JButton in Java:
我在 Java 中有以下 JButton 代码:
enterButton = new JButton("Enter");
enterButton.setMnemonic(KeyEvent.VK_ENTER); // Shortcut: Alt + Enter
The question is simply: Instead of having the shortcut "Alt+Enter", how do I set a shortcut "Enter"?
问题很简单:如何设置快捷方式“Enter”而不是“Alt+Enter”快捷方式?
I simply prefer pressing "Enter" instead of holding "Alt" and pressing "Enter"
我更喜欢按“Enter”而不是按住“Alt”再按“Enter”
回答by Héctor van den Boorn
I had the same issue: I have a form an whenever I am edditing a field I want to press enter for it to fire the actionPerformed event.
我遇到了同样的问题:每当我编辑一个字段时,我都有一个表单,我想按 Enter 键以触发 actionPerformed 事件。
I fixed it with this:
The JPanel
the button and the rest of the form is located on is called content
:
content.getRootPane().setDefaultButton(enterButton);
我用这个修复了它:JPanel
按钮和表单的其余部分位于被称为content
:
content.getRootPane().setDefaultButton(enterButton);
This keeps the button always selected so when you press enter, its corresponding actionPerformed event fires (remember to add an ActionListener to it!)
这使按钮始终处于选中状态,因此当您按下 Enter 键时,会触发其相应的 actionPerformed 事件(记得向其添加 ActionListener!)
Hope this helps you!
希望这对你有帮助!
Kind regards,
Héctor
亲切的问候,
赫克托
回答by Hovercraft Full Of Eels
You can make a button respond to the Enter keyword, via a special technique, one that only works for the Enter key, and to do this you want to get the JRootPane of the top level window that displays the button and call setDefaultButton(myButton)
on this root pane.
您可以通过一种特殊技术使按钮响应 Enter 关键字,该技术仅适用于 Enter 键,为此您需要获取显示按钮的顶级窗口的 JRootPane 并setDefaultButton(myButton)
在此根窗格上调用.
i.e.,
IE,
enterButton = new JButton("Enter")
// after the enterButton has been added to the GUI and the GUI displayed, call:
JRootPane rootPane = SwingUtilities.getRootPane(enterButton);
rootPane.setDefaultButton(enterButton);
Otherwise for non-enter keys, you'd need to use Key Bindings which is do-able, but would require a bit more effort.
否则对于非输入键,您需要使用键绑定,这是可行的,但需要更多的努力。