按下回车键时,Java 将焦点设置在 jbutton 上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4810850/
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-10-30 08:08:03  来源:igfitidea点击:

Java set focus on jbutton when pressing enter

javaswingfocusjbutton

提问by LOD121

How can I make it so that when I press enter in a JTextField it activates a specific JButton? What I mean is something along the lines of a web page form where you can press enter to activate the button in the form. Thanks.

我怎样才能做到当我在 JTextField 中按下 Enter 键时它会激活一个特定的 JButton?我的意思是类似于网页表单的内容,您可以在其中按 Enter 以激活表单中的按钮。谢谢。

回答by Jonas

You should use an Actionfor the JButton:

您应该使用 anAction来表示JButton

Action sendAction = new AbstractAction("Send") {
    public void actionPerformed(ActionEvent e) {
         // do something
    }
};

JButton  button = new JButton(sendAction);

Then you can set the same action for a JTextFieldor even on a MenuItemif you want the same action to be available in the Menu:

然后JTextFieldMenuItem如果您希望菜单中提供相同的操作,您可以为 a或什至在 a 上设置相同的操作:

JTextField textField = new JTextField();
textField.setAction(sendAction);

回答by Uhlen

Something like this should work:

这样的事情应该工作:

textField.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        button.requestFocusInWindow();
    }
});

回答by sunil

You can achieve this by adding the defaultbehavior to the button, like this

您可以通过将default行为添加到按钮来实现这一点,就像这样

cmdLogin.setDefaultCapable(true); // by default, this is true
this.getRootPane().setDefaultButton(cmdLogin); // here `this` is your parent container

回答by Michael Berry

I'd do something like the following:

我会做类似以下的事情:

textField.addKeyListener(
  new KeyAdapter() {
     public void keyPressed(KeyEvent e) {
       if (e.getKeyCode() == KeyEvent.VK_ENTER) {
          button.doClick();
       }
     }
  });
}