2

I need to populate JPassword field. However it looks like there is no method setPassword (char [])

The only method for this is to setText . However I will need to feed a String

Since getText is deprecated , so I presume setText will also be deprecated.

Here is an extract from an answer on stackoverflow

When calling getText you get a String (immutable object) that may not be changed (except reflection) and so the password stays in the memory until garbage collected

So does the same thing happen when I setText . I feed a String and it stays in memory. Why isn't setText deprecated? Why isn't there a setPassword (char []) method ?

Community
  • 1
  • 1
john
  • 647
  • 5
  • 23
  • 53
  • 1
    Here is an example that uses the field's `PlainDocument` and a char array (that you may want to clear once the document has been populated) : http://stackoverflow.com/questions/26975275/fill-a-jpasswordfield-programmatically-without-creating-a-string-object – Arnaud Jul 04 '16 at 15:40
  • Looks like that could work. – john Jul 04 '16 at 15:44

1 Answers1

1

Why isn't there a setPassword (char []) method ?

Whether you insert a String or a char array in the end it's the same.

... so I presume setText will also be deprecated.

No it won't. Usually the user will type in a password. And if you store your passwords somewhere they need to be decrypted and inserted in this field before you can send them.

Shiro
  • 2,610
  • 2
  • 20
  • 36
  • 1
    Thank you very much. I keep password in `byte []` in the database. Then I convert it to `char []`. I was expecting to have a method `setPassword (char [])` to render password to `JPasswordField` . However, it looks like I will need to convert `byte []` to `String` as follows `new String (bytePassword, "UTF-8")` and then feed it to `JPasswordField` . This will create a password `String` in the memory , which could be accidentally flushed to console unless it's picked up by the garbage collector – john Jul 04 '16 at 15:40
  • 2
    As john said, being forced to specify the password as a `String` kinda defeats the purpose, and IMO `setText` should be deprecated. Why depend on the security of using a `char[]` if you have to create a `String` containing the password anyways? – Vince Jul 04 '16 at 16:31