mrspy1100
mrspy1100

Reputation: 41

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

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

Upvotes: 3

Views: 27859

Answers (3)

Prasad Karunagoda
Prasad Karunagoda

Reputation: 2148

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

Upvotes: 7

moskito-x
moskito-x

Reputation: 11968

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

Upvotes: 2

Jeffrey
Jeffrey

Reputation: 44808

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

Upvotes: 9

Related Questions