Java 在面板中按下 ENTER 键时执行 JButton - Swing
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21595590/
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
Execute JButton when ENTER key is pressed in panel - Swing
提问by 1CzDx
I have LoginJButton
on a panel and I need to execute it when I press ENTERkey.
我LoginJButton
在面板上,我需要在ENTER按键时执行它。
Do we have any code snippet for that?
我们有任何代码片段吗?
回答by ravibagul91
To have initial focus on your button you can do something like this:
要最初关注您的按钮,您可以执行以下操作:
frame.getRootPane().setDefaultButton(buttonName);
buttonName.requestFocus();
//Or you can bind your Enter
key to JComponent
and JButton
as:
//或者您可以将您的Enter
密钥绑定到JComponent
和JButton
作为:
AbstractAction action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JButton){
JButton button = (JButton) e.getSource();
button.doClick();
} else if(e.getSource() instanceof JComponent){
JComponent component = (JComponent) e.getSource();
component.transferFocus();
}
}
};
//You can bind key to JComponent like:
//您可以将键绑定到 JComponent,例如:
jComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "TransferFocus");
jComponent.getActionMap().put("TransferFocus", action);
//You can bind key to JButton like:
//您可以将键绑定到JButton,例如:
jButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "DoClick");
jButton.getActionMap().put("DoClick", action);
Useful Link
有用的链接
回答by JavaTechnical
You can use InputMap
and ActionMap
to do this.
您可以使用InputMap
和ActionMap
来做到这一点。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ac1
{
public static void main(String args[])
{
JFrame f=new JFrame();
f.setVisible(true);
f.setSize(400,400);
f.setLayout(new FlowLayout());
final JButton b=new JButton("button");
f.add(b);
f.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDO
W).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),"clickButton");
f.getRootPane().getActionMap().put("clickButton",new AbstractAction(){
public void actionPerformed(ActionEvent ae)
{
b.doClick();
System.out.println("button clicked");
}
});
}
}