Java set focus on jbutton when pressing enter

LOD121 picture LOD121 · Jan 26, 2011 · Viewed 13.3k times · Source

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.

Answer

Jonas picture Jonas · Jan 26, 2011

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