PasswordFieldEchoChar.java Source code

Java tutorial

Introduction

Here is the source code for PasswordFieldEchoChar.java

Source

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 PasswordFieldEchoChar extends JFrame {
    public static void main(String[] args) {
        PasswordFieldEchoChar that = new PasswordFieldEchoChar();
        that.setVisible(true);
    }

    public PasswordFieldEchoChar() {
        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);
        pwf.setEchoChar('#');
        add(pwf);

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