I am making a command line program and i need to test to see if the enter key is pressed.
Asked
Active
Viewed 2.7k times
3 Answers
9
If the enter key is pressed in a JTextField
while that JTextField
has ActionListener
s, an ActionEvent
is fired.
JTextField field = ...
field.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Enter key pressed");
}
});

Jeffrey
- 44,417
- 8
- 90
- 141
-
1Where is it checking that it is the Enter key that was pressed? What about if other actions took place within the textfield? – ziggy Jan 27 '13 at 12:52
-
@ziggy One of the default entries in the [`InputMap`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#getInputMap()) detects when a `pressed Enter` event passes through the [`processKeyBinding`](http://tinyurl.com/ay3kqzt) method. It then invokes an `Action` which fires an `ActionEvent`. – Jeffrey Jan 27 '13 at 17:10
7
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);
}
}

Prasad Karunagoda
- 2,048
- 2
- 12
- 16
-
This answer is more accurate than the first one as it detects either really enter was pressed. Thanks – Airy Nov 01 '14 at 07:46
2
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