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.
|
|
|
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.