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 ActionListener
s, 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
Author by
mrspy1100
Updated on May 25, 2020Comments
-
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 over 11 yearsWhere is it checking that it is the Enter key that was pressed? What about if other actions took place within the textfield?
-
Jeffrey over 11 years@ziggy One of the default entries in the
InputMap
detects when apressed Enter
event passes through theprocessKeyBinding
method. It then invokes anAction
which fires anActionEvent
. -
Airy over 9 yearsThis answer is more accurate than the first one as it detects either really enter was pressed. Thanks