How to Limit number of lines in JTextArea?

Ralph Andreasen picture Ralph Andreasen · Aug 28, 2012 · Viewed 13.3k times · Source

I am trying to make a GUI for a service, which have a JTextArea to view messages in, each message is written on a single line, and wordwrapped if needed.

The messages arrive via a socket, so it is merely an .append(message) that i am using to update the JTextArea, i need to limit these lines to 50 or 100 and i have no need to limit character count on each line.

If there is a method to limit the number lines in the JTextArea or if there is an alternative method of doing it?

I could really use the assistance in this matter.

Edit

The problem is that each client can send infinite lines, all these lines have to be readable, so this is not a simple check of the number of lines in the JTextArea. I need to remove older lines in order to view newer lines.

Answer

StanislavL picture StanislavL · Aug 28, 2012

Use this to get row and column

Add a DocumentFilter which checks amount of rows (pass the doc.getLength() offset) and prevent adding more text.

Or you can create a dummy invisible JTextArea and add all the text there. Then measure last allowed line and cut the text.