Question

In a JFrame class I have a JPasswordField object, something like this:

pswdTextField = new JPasswordField(20);
externalPanel.add(pswdTextField, "w 90%, wrap");

I try to access to its inserted content (the password inserted by a user) by the following lines of code:

char[] pswd = pswdTextField.getPassword();
System.out.println("Password: " + pswd.toString());

The problem is that when I go to print this content I obtain the following output: Password: [C@d5c0f9 and not the inserted password

Why? What is it means? How can I obtain the inserted password?

Tnx

Andrea

Was it helpful?

Solution

Why? What is it means?

If you go through docs than you got this reasons.

For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.

How can I obtain the inserted password?

You can get password by,

  char[] pswd = pswdTextField.getPassword();
  String password=new String(pswd);

Or, you can directly print on System.out.print

  System.out.print(pswd); // It override ...print(char[]) method
                          // without concat with another String.

Edit

Please note that, If you concat char[] with String than it will inherit Object.toString() method.

 System.out.print("Password: " +pswd);// It will print like Password: [C@d5c0f9

OTHER TIPS

pswdTextField.getText() is what you were looking for. toString() will not return the text inside a JPasswordField().

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of: getClass().getName() + '@' + Integer.toHexString(hashCode())

so use

System.out.println("Password: " +pswdTextField.getText());

getText() is depreciated for JPasswordField

in Java source, its written above getText() definition

" For security reasons, this method is deprecated. "

so getPassword() is preferred. The problem you are facing is that you are printing an array using System.out.println() either create a string using that character array or use for loop to access each element one by one

for(int i=0;i < charArray.length;i++)

System.out.print (charArray[i]);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top