devxlogo

TextArea With Word Wrap

TextArea With Word Wrap

The default behavior for a java.awt.TextArea is to scroll the text you enter to the left once the length of the line of text exceeds the displayable area. When this occurs, a horizontal scroll bar at the bottom of the component allows you to scroll left and right to review the full text. However, in many cases, this may not be the desired behavior. You’ll often want “word wrap” to occur instead, where a word is automatically moved to a new line as the user is typing it if the word is too long to fit on the current line. Even the most simplistic word processors usually support this feature, and its absence can be a great source of frustration for users. Fortunately, there is a simple way to cause TextArea instances to automatically handle word wrap for you. When instantiating the TextArea, specify that there should not be a horizontal scrollbar (using SCROLLBARS_VERTICAL_ONLY), and instead of scrolling text off the visible area of the component, it will use word wrapping to break the text down into separate lines. For example, this code will instantiate a TextArea that displays 4 rows of 30 columns each, with no initial text and provides automatic word wrapping:

 TextArea ta = new TextArea("", 4, 30, TextArea.SCROLLBARS_VERTICAL_ONLY);

devx-admin

Share the Post: