Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
Halo Avatar asked Dec 22 '22 04:12

Halo


2 Answers

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

like image 55
Aaron Digulla Avatar answered Dec 28 '22 06:12

Aaron Digulla


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.

like image 39
Hillary Ryan Avatar answered Dec 28 '22 07:12

Hillary Ryan