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?
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).
I had the same problem. From my tests, I do not believe that the JTextArea sets its size dynamically. Instead, its size seems to be limited by its container (a JPanel in my case). However, the JTextArea does change its preferred size based on the text it contains. From the documentation:
java.awt.TextArea has two properties rows and columns that are used to determine the preferred size. JTextArea uses these properties to indicate the preferred size of the viewport when placed inside a JScrollPane to match the functionality provided by java.awt.TextArea. JTextArea has a preferred size of what is needed to display all of the text, so that it functions properly inside of a JScrollPane. If the value for rows or columns is equal to zero, the preferred size along that axis is used for the viewport preferred size along the same axis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With