Single Line Text Area
Posted by Rob Camick on January 15, 2009
We all know that a JTextField is used to display a single line of text and a JTextArea is used to display multiple lines of text. A text area also has the ability to wrap an individual line of text. Maybe you have a need for a text field that has the ability to wrap text.
Well, you can’t teach the text field a new trick, but you can teach the text area a new trick. That is, we can use a text area to prevent new lines characters from being inserted into the document. Therefore, all the text in the text area will be treated as a single line of text. If you now turn wrapping on, you have effectively created a text field with wrapping.
This feature is added to a text area with the following code:
Now as text is inserted into the document all new line strings are replaced with a space.
Note, that this feature will only work on a PlainDocument, which is the default Document for a text areas and text fields. Also, as you may have guessed, this is the default property for a text field.