开发者

Java set focus on JButton when pressing enter

开发者 https://www.devze.com 2023-02-07 10:37 出处:网络
How can I make it so tha开发者_JAVA百科t 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 ac

How can I make it so tha开发者_JAVA百科t 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.


You should use an Action for the 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 JTextField or even on a MenuItem if you want the same action to be available in the Menu:

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


Something like this should work:

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


You can achieve this by adding the default behavior to the button, like this

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


I'd do something like the following:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号