Java Tips Weblog

  • Blog Stats

    • 1,983,340 hits
  • Categories

  • Archives

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

Get The Code

Related Reading

How to Write a Document Listener


3 Responses to “Limit Lines in Document”

  1. Anonymous said

    thanks, my GUI has no exceptions anymore :)

  2. teo said

    thank you thank you thank you very much!

  3. Anonymous said

    thanks a lot!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s