This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I'd like to be able to enter multi-line text into an application, yet not have the text returned as a String. Instead I'd like it to be returned as a clearable char. JPasswordField allows a char output, but, alas, is for single line only.
The problem isn't in converting a String to a char. It's having an unclearable, immutable String representation of the text in memory. That's why the JPasswordField class has a char output and the String outputs are deprecated.
To demonstrate String x = "Secret" isn't cleared by a subsequent x = "" statement. The String content "Secret" is no longer accessible, but it's somewhere on the computer. With a char, the data can be overwritten and the original contents are lost and gone forever, as intended.
The suggestion of extending JTextArea seemed pretty complicated.
JTextComponent is a predecessor of JTextField and offers a getDocument() method. If I retrieve the Document, then the Document getText(int, int, Segment) is available. In Segment a char of text is a field. Presumably I could copy the text as a char from that field and put trash back into the field's char afterwards.
The javax.swing.text.Segment docs says "It should be treated as immutable even though the array is directly accessible. This gives fast access to fragments of text without the overhead of copying around characters. This is effectively an unprotected String. "
Was this what was suggested and does this seem a reasonable approach?
If you take a look at the source code of JPasswordField (available in the src.zip file inside your JDK installation folder), you will see that getPassword() is implemented like this:
As you see, that indeed uses a Segment. The BadLocationException shouldn't occur unless someone is not respecting the Swing threading rules (from Concurrency in Swing).
FYI, getText() is inherited from JTextComponent and is implemented like this: