Java Swing How to - Handle action event on JPasswordField, trigger by pressing Enter key








Question

We would like to know how to handle action event on JPasswordField, trigger by pressing Enter key.

Answer

 /*from  w  ww  .  j av a 2  s .com*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPasswordField;

public class Main extends JFrame {
  JPasswordField field = new JPasswordField("*", 10);

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    field.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Field=" + field.getText());
      }
    });

    getContentPane().add(field);
    pack();
    setVisible(true);
  }

  public static void main(String arg[]) {
    new Main();
  }
}