Java Tips Weblog

  • Blog Stats

    • 2,065,822 hits
  • Categories

  • Archives

  • Advertisements

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:

textArea.getDocument().putProperty("filterNewlines", Boolean.TRUE);

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: