按Enter键时,Java将焦点设置在jbutton上

LOD*_*121 10 java swing focus jbutton

我怎样才能这样做,当我在JTextField中按Enter键时,它会激活一个特定的JButton?我的意思是网页表单中的某些内容,您可以按Enter键激活表单中的按钮.谢谢.

Jon*_*nas 13

您应该使用ActionJButton:

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

JButton  button = new JButton(sendAction);
Run Code Online (Sandbox Code Playgroud)

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

JTextField textField = new JTextField();
textField.setAction(sendAction);
Run Code Online (Sandbox Code Playgroud)

  • +1,很酷,我甚至都不知道setAction()方法.我一直使用addActionListener.无论哪种方式,这都是更好的解决方案. (5认同)

Uhl*_*len 7

这样的事情应该有效:

textField.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        button.requestFocusInWindow();
    }
});
Run Code Online (Sandbox Code Playgroud)

  • @ LOD121,这不是正确的解决方案. (2认同)

sun*_*nil 5

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

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