Java Swing How to - Handle key event on JPasswordField








Question

We would like to know how to handle key event on JPasswordField.

Answer

 /* ww w  .  j  av a 2  s .  c om*/
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

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

public class Main extends JFrame {
  public static void main(String[] args) {
    Main that = new Main();
    that.setVisible(true);
  }

  public Main() {
    setSize(450, 350);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().add(new PasswordPanel(), BorderLayout.SOUTH);
  }
}

class PasswordPanel extends JPanel {
  JPasswordField pwf;

  public PasswordPanel() {
    pwf = new JPasswordField(10);
    add(pwf);

    pwf.addKeyListener(new KeyAdapter() {
      public void keyReleased(KeyEvent e) {
        System.out.println(new String(pwf.getPassword()));
      }
    });
  }
}