Question:
How do I access the contents of a JPasswordField to see if it matches
with the correct password?
Answer:
Before using a class, it helps to examine all of the documentation for
its superclasses because certain pieces of functionality may be
provided in inherited methods, rather than ones defined only in the
subclass. JPasswordField is a little bit odd in this respect. It is
derived from JTextField, which is in turn derived from
JTextComponent.
JTextComponent defines the getText() method, which
you would normally use to retrieve the content of a text component as a
Java String. In the original version of the Swing classes, getText() was
the proper way of retrieving the password contained in a
JPasswordField. But it was realized that this presented a potential
security problem. Strings are immutable, making it impossible to
quickly erase the password from memory immediately after use.
Therefore, the getText() method has been deprecated in JPasswordField
and replaced with getPassword(), which returns the password as a
character array. Immediately after manipulating the password, you
should clear the elements of the character array to ensure it does not
linger unencrypted in memory.