datalogo
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com

Creating a JPasswordField

The JPasswordField is a subclass of JTextField. It allows a one line of text entry, but it hides the typed characters behind a series of dots (referred to as "echo" characters) for security purposes.

With the JTextField and JTextArea, the getText( ) method is used to retrieve the text that is entered by the user into the field or area. In JPasswordField, we will be using the getPassword( ) method to retrieve the entered password. In the JPasswordField class, this has been an update in Java coding.

The getText( ) method returns a String. But the getPassword( ) method returns a char array, for security purposes. This will need to be taken into consideration when trying to determine if the typed password is correct.

Why is a character array safer than a String?

In Java, String is an immutable object (meaning it cannot be changed in memory once it is created). Yes, you can edit the String to obtain a new version of the String, but the original version (obtained by getText()) will remain in the String pool. This means that as a String, a "password" will remain in the memory longer than you may think, making it potentially retrievable by malware.

By creating a character array for the "password", you are allowing the password to be modified and not remain in memory.
passwordThinker

dividerdash

JPasswordField

reddot JPasswordField( ) - creates a new password field (0 column width, null String)
reddot JPasswordField(int columns) - creates a new password field with given number of columns
reddot JPasswordField(String text) - creates a new password field with specified text
reddot JPasswordField(String text, int columns) - creates a new password field with specified text and columns

dividerdash

JPasswordField field;
char[ ] passwordenter;
field = new JPasswordField();
field.setBounds(120,78,200,30);
panel.add(field);

Example: The user is asked to submit the password needed to view an on-line movie. The needed password is "butterfly". When SUBMIT is clicked, "Correct" or "Not Correct" will appear above the entry field.

In this example, a method called CheckingPassword is created by the programmer and is used to determine if the user-entered password is correct.

 pw7 pw8

pw9
pw6

divider
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com

Notice: These materials are free for your on-line use at this site, but are not free for the taking.
Please do not copy these materials or re-post them to the Internet, as it is copyright infringement.
If you wish hard-copies of these materials, refer to our subscription area, JavaMathBits.com.
Help us keep these resources free. Thank you.