Search code examples
javaswinguser-interfacejpasswordfield

How to access to the text inside a Swing JPasswordField object?


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


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