2

I'm trying to make it so that when the user presses the Enter key the JButton which is associated with that key gets triggered.

Here's what my code looks like:

import java.awt.event.KeyEvent;

private void formKeyPressed(java.awt.event.KeyEvent evt) {
      if(evt.getKeyCode()==KeyEvent.VK_ENTER) {
          jButton2.setEnabled(true);
   }
}    
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Marcell
  • 23
  • 1
  • 3

2 Answers2

2

How to trigger a JButton with a key press?

Add an ActionListener to the button. It will fire an event when the button is in focus and the user presses the enter key. See How to Write an Action Listener for more info.

Edit

See also further details in Rob Camick's Enter Key and Button.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    (1+) Definitely should be adding the ActionListener to the button (not a MouseListener). But the invoking of the Action when the Enter key is pressed can be a LAF issue. Check out [Button and Enter Key](https://tips4java.wordpress.com/2008/10/25/enter-key-and-button/) for more information. – camickr Jun 17 '18 at 17:19
0

ActionListener itself won't be sufficient. You will have to write a KeyListener to get this thing down. A KeyListener which captures Enter button press would look like this.

this.button.addKeyListener(new KeyListener() {

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            System.out.println("Hello");
            JOptionPane.showMessageDialog(null, "Enter key pressed !");
        }

    }
});
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63