Search code examples
javajtextareaautoresize

Auto-Resizing JTextArea


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?


Solution

  • 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).