JPasswordField is a subclass of the JTextField so it acts like an ordinary text field but it hides the actual characters typed by showing a series of echo characters such as asterisks (*) or a dots, for security purpose. For example:

a JPasswordField

In this article, we provide a summary of the common and recommended practices when working with JPasswordField in Swing, with code examples and a demo program.

Table of content

    1. Creating new JPasswordField object
    2. Adding the password field to a container
    3. Setting and getting password
    4. Adding event listeners
    5. Selecting text
    6. Customizing appearance
    7. A demo program for JPasswordField

A typical usage of JPasswordField looks like this:

// create new object
JPasswordField passwordField = new JPasswordField(20);

// add to the container
frame.add(passwordField);

// get the password
char[] password = passwordField.getPassword();

Let’s dive into more details.

 

1. Creating new JPasswordField object

When creating a new JPasswordField object, we can specify an initial text and the field’s width in number of columns, using one of the following constructors:

JPasswordField(int columns)

JPasswordField(String text)

JPasswordField(String text, int columns)

Note that the parameter columns specifies minimum width of the field in a number of columns, not in number of pixels nor characters. Here are some examples:

JPasswordField passwordField = new JPasswordField(20);

JPasswordField passwordField = new JPasswordField("secret");

JPasswordField passwordField = new JPasswordField("secret", 20);

We can also use an empty constructor to create new object and then set the columns and initial password later, for example:

JPasswordField passwordField = new JPasswordField(20);
passwordField.setColumns(10);
passwordField.setText("secret");

NOTE: Like other Swing components, the JPasswordField class resides in the package javax.swing.

 

Related Course: Java Swing (GUI) Programming: From Beginner to Expert


2. Adding the password field to a container

The password field cannot stand alone. It must be added to a parent container such as JFrame or JPanel. For example:

frame.add(passwordField);
panel.add(passwordField);

Adding to a JFrame with BorderLayout:

frame.add(passwordField, BorderLayout.NORTH);

Adding to a JFrame with GridBagLayout:

GridBagConstraints constraints = new GridBagConstraints();
// set constraints...

frame.add(passwordField, constraints);


3. Setting and getting password

Use the setText() method (inherited from javax.swing.text.JTextComponent class) to set password for the field:

passwordField.setText("secret");

To retrieve password typed into the field, use the getPassword() method:

char[] password = passwordField.getPassword();

For security purpose, the getPassword() method returns a char array instead of a String object. So it’s RECOMMENDED to compare the password as follows:

char[] password = passwordField.getPassword();
char[] correctPass = new char[] {'s', 'e', 'c', 'r', 'e', 't'};

if (Arrays.equals(password, correctPass)) {
	System.out.println("Password is correct");
} else {
	System.out.println("Incorrect password");
}

In the above code snippet, we use the method equals() of the java.util.Arrays class to compare two char arrays.

AVOID getting the password as follows:

String password = new String(passwordField.getPassword());

AVOID comparing the password as follows:

String password = new String(passwordField.getPassword());
if (password.equals("secret")) {
	// password is correct
}

It’s also recommended to clear the char array when we are finished using it (for enhanced security):

Arrays.fill(correctPass, '0');

NOTE: The getText() method is deprecated in JPasswordField class because it returns password as a String object which might be vulnerable for security.

 

Learn Swing in Swing: A Beginner's Guide

 


4. Adding event listeners

We can add a listener for the event in which the user presses Enter key after typing text into the field. For example:

passwordField.addActionListener(new ActionListener() {
	@Override
	public void actionPerformed(ActionEvent event) {
		JPasswordField field = (JPasswordField) event.getSource();
		char[] password = field.getPassword();

		if (password.length < 8) {
			System.out.println("Password must contain at least 8 characters!");
		}
	}
});

The above code will check for length of the entered password as soon as the user hits Enter key.

We can also add a listener to handle key events which are fired whenever the user types a character into the field. For example:

passwordField.addKeyListener(new KeyListener() {

	@Override
	public void keyTyped(KeyEvent event) {
		// do something when a key has been typed
	}

	@Override
	public void keyReleased(KeyEvent event) {
		// do something when a key has been released
	}

	@Override
	public void keyPressed(KeyEvent event) {
		// do something when a key has been pressed
	}
});

A typical usage of key event listener is to check emptiness of the field in order to enable/disable the action button accordingly, for example:

passwordField.addKeyListener(new KeyAdapter() {
	@Override
	public void keyReleased(KeyEvent event) {
		JPasswordField field = (JPasswordField) event.getSource();
		char[] password = field.getPassword();

		if (password == null || password.length == 0) {
			actionButton.setEnabled(false);
		} else {
			actionButton.setEnabled(true);
		}
	}
});

Notice in the above code snippet, we create an anonymous class that extends the KeyAdapter class, instead of implementing the KeyListener interface, so we can override only the interested method.

 


5. Selecting text

Select all text in the field:

passwordField.selectAll();

The selection looks like this:

select all text in JPasswordField


6. Customizing appearance

  • Set echo character:
    passwordField.setEchoChar('*');
    

    Image:
    set asterisk as echo character for JPasswordField

     

  • Set font style, background and foreground colors:
    passwordField.setFont(new java.awt.Font("Arial", Font.BOLD, 20));
    passwordField.setBackground(Color.YELLOW);
    passwordField.setForeground(Color.BLUE);
    

    Image:
    customize JPasswordField appearance

     

  • Set tooltip text:
passwordField.setToolTipText("Password must contain at least 8 characters");


Image:
set tooltip text for JPasswordField

 


7. A demo program for JPasswordField

For reference, we created a sample program looks like this:

Swing JPasswordField demo program

This program displays two password fields and verifies if the passwords are matched and correct.

On clicking the OK button, if the two passwords are not matched, the following message appears:

dialog message for passwords do not match

If the two passwords are matched, but do not equal to “codejava”, this message appears:

message dialog for wrong password

And if the both passwords equal to “codejava”, this message appears:

message dialog for correct passwords

You can download full source code of the demo program as well as its runnable jar file in the attachments section below.

 

Learn Advanced Swing techniques in Core Java, Volume II--Advanced Features (9th Edition)

Submit to DeliciousSubmit to DiggSubmit to FacebookSubmit to Google BookmarksSubmit to StumbleuponSubmit to TechnoratiSubmit to TwitterSubmit to LinkedIn
Attachments:
Download this file (SwingJPasswordFieldDemo.zip)SwingJPasswordFieldDemo.zip[Source code and runnable jar file]9 kB