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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:33:45  来源:igfitidea点击:

Execute JButton when ENTER key is pressed in panel - Swing

javaswingjbuttonkeyevent

提问by 1CzDx

I have LoginJButtonon 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 Enterkey to JComponentand JButtonas:

//或者您可以将您的Enter密钥绑定到JComponentJButton作为:

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

有用的链接

How to Use the Focus Subsystem

如何使用焦点子系统

回答by JavaTechnical

You can use InputMapand ActionMapto do this.

您可以使用InputMapActionMap来做到这一点。

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");
        }
    });
    }
}