devxlogo

JPasswordField

JPasswordField

Question:
How do I access the contents of a JPasswordField to see if it matcheswith the correct password?

Answer:
Before using a class, it helps to examine all of the documentation forits superclasses because certain pieces of functionality may beprovided in inherited methods, rather than ones defined only in thesubclass. JPasswordField is a little bit odd in this respect. It isderived from JTextField, which is in turn derived fromJTextComponent.

JTextComponent defines the getText() method, whichyou would normally use to retrieve the content of a text component as aJava String. In the original version of the Swing classes, getText() wasthe proper way of retrieving the password contained in aJPasswordField. But it was realized that this presented a potentialsecurity problem. Strings are immutable, making it impossible toquickly erase the password from memory immediately after use.

Therefore, the getText() method has been deprecated in JPasswordFieldand replaced with getPassword(), which returns the password as acharacter array. Immediately after manipulating the password, youshould clear the elements of the character array to ensure it does notlinger unencrypted in memory.

devx-admin

Share the Post: