7

I have an application which continuously receives data on a socket, and then logs this data to a file while also displaying this data in a JTextPane. Naturally, as data is written to the underlying document of the JTextPane the memory usage continues to increase.

Is there a simple way of limiting the memory which the JTextPane is allowed use? I would like the JTextPane to work similar to how a typical command shell's command history works.

tjansson
  • 324
  • 2
  • 11

2 Answers2

7

just check the content and wipe it accordingly to a maximum buffer size.. since it's a JTextPane you would work on document class used by textpane:

void clampBuffer(int incomingDataSize)
{
   Document doc = textPane.getStyledDocument();
   int overLength = doc.getLength() + incomingDataSize - BUFFER_SIZE;

   if (overLength > 0)
   {
      doc.remove(0, over_length);
   }
}

This is just a snippet I wrote, didn't check it personally.. it's just to give you the idea. Of course it should be run before adding text to textPane.

Btw if you are not using the rich editor capabilities of the JTextPane I suggest you to use a JTextArea that is much ligher.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • This does not work, you might think it does, but it doesnt, and I have the same issue in an app of mine. Imagine a JTextPane and you constantly adding lines to it from a source, if line number is over 100, remove line 0, then add new line. This should keep the memory usage at roughly the same level, right? Wrong... over time my java app explodes and after an hour already as 170MB memory usage, with only 100 lines of small text. I have absolutely no idea why, or how to fix this... – M. H. Jul 07 '17 at 12:13
0

Nope, you have to count characters as you add text, and delete some when you think it's too much.

Note that JTextPane has a DocumentModel underneath it which can give you access to character counts and also make deletions a little handier maybe.

Carl Smotricz
  • 66,391
  • 18
  • 125
  • 167