Limit Lines in Document
Posted by Rob Camick on October 15, 2008
You may want to use a JTextArea or JTextPane as a simple console type component. That is, messages from your application will be added to the console as they are generated. Now you will probably need the ability to limit the total number of messages in the console so that you don’t run out of memory. How can we do this?
Well, we must remember that every text component uses a Document to store the text. Therefore, we will need to monitor changes to the Document. This is easily accomplished by adding a DocumentListener to the Document. Now all we have to do is handle the insertUpate(…) method of the DocumentListener interface and we are in business.
The LimitLinesDocumentListener class does just this. Every time even a single character is added to the Document, this class will check the current number of lines. When the curent number of lines exceeds the maximum, lines of text will be removed from the Document. The only other choice you need to make is whether you remove the lines from the start or end of the Document:
- start (the default) – would be used when your application appends text to the Document (ie. all new text is displayed at the botton of your console)
- end – would be used when your application inserts text at the start of the Document (ie. all the new text is displayed at the top of your console)
You get all this functionality with a single line of code:
new LimitLinesDocumentListener(50) );