Java Swing How to - Add ActionListener to JTextField and react the enter key pressed








Question

We would like to know how to add ActionListener to JTextField and react the enter key pressed.

Answer

 //from ww  w  .j av a 2 s.  c  o m


import java.awt.event.ActionEvent;

import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Main {

  public static void main(String[] a) {
    JTextField jTextField1 = new JTextField();

    jTextField1.setText("java2s.com");

    jTextField1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("action");
      }
    });
    JOptionPane.showMessageDialog(null,jTextField1);
  }
}