Auto-Resizing JTextArea

Halo picture Halo · Apr 8, 2010 · Viewed 15.4k times · Source

I want my JTextArea to resize itself (expand vertically) when the last line (that the text area's height can offer) is reached and the user wants to start a new line. You know, like the textbox in MSWord.

I have an idea to use getLineCount() and determine (if necessary) the new height of the JTextArea. Do you have, or know of better approaches for implementing this?

Answer

Aaron Digulla picture Aaron Digulla · Apr 8, 2010

Actually, the JTextArea always has the correct size so all lines of text are visible. What you experience is probably that you wrapped the text area in a JScrollPane. Just omit the scroll pane and make the text area a direct child of the container.

Another solution is to listen to resize events of the text area and size the scroll pane accordingly. This way, you can grow to a certain size and then start to display scroll bars (for example, when someone pastes 500KB of text into the text area).