Java Swing – JPasswordField Tutorial with Programming Example

It is a subclass of JTextField class. This field doesn’t show characters and put * (asterisk) at the place of entered characters. It hides text behind asterisk (*).

Purpose of JPasswordField

JPasswordField adds extra security to your apps. While typing a password or setting a new password, it is compulsory that your password is hidden from others. If you don’t use JPasswordField then your password might be viewed by others.

Programming Example

Output

Formatting JPasswordField

You can set custom characters instead of ‘*’.

pwdfield.setEchoChar('#');

Getting Password from JPasswordField

Note: You must use Arrays.fill() method to remove password from char array for enhanced security.

Output

Don’t use following methods to get a password from JPasswordField component.

It is vulnerable to use String to gather password from JPasswordField area. You always use Char[] array to getting a password from JPasswordField.

Adding Event Listener and Key Listener to JPasswordField

You can add Event Listener and Key Listener in JPasswordField in the following manner.

Output

Summary

In this tutorial, you learned how to use JPasswordField in Swing to get or set the user password. In the next chapter, you will learn JTextArea in Java Swing.


Leave a Reply

Your email address will not be published. Required fields are marked *