Java Swing Tutorial - Java Swing JPasswordField

A JPasswordField is a JTextField and it hides the characters typed in.

We can set our own echo character by using its setEchoChar(char newEchoChar) method.

The JPasswordField class has the same set of constructors as the JTextField class.

We combine the initial text, the number of columns, and a Document object to create a JPasswordField object.

To create a password field 10 characters wide

JPasswordField passwordField = new JPasswordField(10);

The getText() method for JPasswordField has been deprecated for security reasons.

We should use its getPassword() method instead, which returns an array of char.

The following code shows how to validate a password entered in a JPasswordField:

First, get the password entered in the field.

char c[] = passwordField.getPassword();

String correctPass = "myPassword";
char[] cp  = correctPass.toCharArray();

if (Arrays.equals(c,  cp)) {
  System.out.println("The password is correct");
else  {
  System.out.println("The password  is incorrect");

The following code sets # as the echo character.


We can use a JPasswordField as a JTextField by setting its echo character to zero.

The following code sets echo character to 0, so the actual password characters are visible.

import java.awt.BorderLayout;
import java.awt.Container;
/* w ww.jav  a 2s  . c  o m*/
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Main {
  public static void main(String args[]) {
    JFrame f = new JFrame("JPasswordField Sample");
    Container content = f.getContentPane();
    content.setLayout(new BorderLayout());
    Box rowOne = Box.createHorizontalBox();
    rowOne.add(new JLabel("Username"));
    rowOne.add(new JTextField());
    Box rowTwo = Box.createHorizontalBox();
    rowTwo.add(new JLabel("Password"));
    rowTwo.add(new JPasswordField());
    content.add(rowOne, BorderLayout.NORTH);
    content.add(rowTwo, BorderLayout.SOUTH);
    f.setSize(300, 200);