How do i test to see if the enter key is pressed in a textfield in java?

26,543

Solution 1

If the enter key is pressed in a JTextField while that JTextField has ActionListeners, an ActionEvent is fired.

JTextField field = ...
field.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Enter key pressed");
    }
});

Solution 2

Add a key listener to the text field and check KeyEvent's keyCode in keyPressed(). Try the example below:

public class TestEnterKeyPressInJTextField
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField textField = new JTextField(20);
    textField.addKeyListener(new KeyAdapter()
    {
      public void keyPressed(KeyEvent e)
      {
        if (e.getKeyCode() == KeyEvent.VK_ENTER)
        {
          System.out.println("ENTER key pressed");
        }
      }
    });

    frame.getContentPane().add(textField);
    frame.pack();
    frame.setVisible(true);
  }
}

Solution 3

command line program or gui application?

look here for detailed answers

public void keyTyped(KeyEvent e) {
}

public void keyPressed(KeyEvent e) {
    System.out.println("KeyPressed: "+e.getKeyCode()+", ts="+e.getWhen());
}

public void keyReleased(KeyEvent e) {
    System.out.println("KeyReleased: "+e.getKeyCode()+", ts="+e.getWhen());
}

press every key you want and see the KeyCode

Share:
26,543
mrspy1100
Author by

mrspy1100

Updated on May 25, 2020

Comments

  • mrspy1100
    mrspy1100 almost 4 years

    I am making a command line program and i need to test to see if the enter key is pressed.

  • ziggy
    ziggy over 11 years
    Where is it checking that it is the Enter key that was pressed? What about if other actions took place within the textfield?
  • Jeffrey
    Jeffrey over 11 years
    @ziggy One of the default entries in the InputMap detects when a pressed Enter event passes through the processKeyBinding method. It then invokes an Action which fires an ActionEvent.
  • Airy
    Airy over 9 years
    This answer is more accurate than the first one as it detects either really enter was pressed. Thanks