Search code examples
javaswingjtextfield

Detect enter press in JTextField


Is it possible to detect when someone presses Enter while typing in a JTextField in java? Without having to create a button and set it as the default.


Solution

  • A JTextField was designed to use an ActionListener just like a JButton is. See the addActionListener() method of JTextField.

    For example:

    Action action = new AbstractAction()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("some action");
        }
    };
    
    JTextField textField = new JTextField(10);
    textField.addActionListener( action );
    

    Now the event is fired when the Enter key is used.

    Also, an added benefit is that you can share the listener with a button even if you don't want to make the button a default button.

    JButton button = new JButton("Do Something");
    button.addActionListener( action );
    

    Note, this example uses an Action, which implements ActionListener because Action is a newer API with addition features. For example you could disable the Action which would disable the event for both the text field and the button.