Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting JTextArea size to the size of its text

I have a JTextArea of a fixed size (300 x 33) with line wrapping enabled that I have added inside of a JPanel. Whenever one types inside it and goes past the last visible row (in this case the second one), the text continues outside of the text area's view, and is hidden.

Is there anyway to limit the text entered inside of a JTextArea to the size of the text area rather than to the number of characters that it contains (making it dependent to the different space that each character of different fonts occupies)?

Edit: I forgot to mention that not fixing the size of the JTextArea and providing row and column numbers in the constructor would result in the text area to stretch and fill the JPanel holding it. I believe this is due to the fact that the panel's layout is a BoxLayout.

like image 397
JCtrl Avatar asked Nov 17 '25 06:11

JCtrl


1 Answers

You shouldn't fix the size of a JTextArea. Rather initialize it by calling its constructor with decent column and row number parameters, and put it in a JScrollPane so if the text increases, you'll not lose the text.

like image 119
Hovercraft Full Of Eels Avatar answered Nov 19 '25 20:11

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!