2

I'm using JTextPane to log some data from a network application and after the program runs for about more than 10 hours or so I get memory heap error. Text continues to get added to the JTextPane which keeps increasing memory usage. Is there anyway I can make the JTextPane act like a command prompt window? Should I get rid of the old text as new text comes in? This is the method I'm using to write to the JTextPane.

volatile JTextPane textPane = new JTextPane();
public void println(String str, Color color) throws Exception
{
    str = str + "\n";
    StyledDocument doc = textPane.getStyledDocument();
    Style style = textPane.addStyle("I'm a Style", null);
    StyleConstants.setForeground(style, color);
    doc.insertString(doc.getLength(), str, style);
}
Oskar
  • 1,321
  • 9
  • 19
Arya
  • 8,473
  • 27
  • 105
  • 175
  • possible duplicate of [Limit JTextPane memory usage](http://stackoverflow.com/questions/2006615/limit-jtextpane-memory-usage) – tenorsax Jul 14 '12 at 16:50
  • Yes I ran into that but I don't know how to make it work with mine. I will keep trying. – Arya Jul 14 '12 at 16:54

2 Answers2

3

You could remove an equivalent amount from the beginning of the StyledDocument once the its length exceeds a certain limit:

int docLengthMaximum = 10000;
if(doc.getLength() + str.length() > docLengthMaximum) {
    doc.remove(0, str.length());
}
doc.insertString(doc.getLength(), str, style);
Bobulous
  • 12,967
  • 4
  • 37
  • 68
2

You'll want to take advantage of the Documents DocumentFilter

public class SizeFilter extends DocumentFilter {

    private int maxCharacters;
    public SizeFilter(int maxChars) {
        maxCharacters = maxChars;
    }

    public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
        throws BadLocationException {
        if ((fb.getDocument().getLength() + str.length()) > maxCharacters)
            int trim = maxCharacters - (fb.getDocument().getLength() + str.length()); //trim only those characters we need to
            fb.remove(0, trim);
        }
        super.insertString(fb, offs, str, a);
    }

    public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)
        throws BadLocationException {

        if ((fb.getDocument().getLength() + str.length() - length) > maxCharacters) {
            int trim = maxCharacters - (fb.getDocument().getLength() + str.length() - length); // trim only those characters we need to
            fb.remove(0, trim);
        }
        super.replace(fb, offs, length, str, a);
    }
}

Based on character limiter filter from http://www.jroller.com/dpmihai/entry/documentfilter

You will need to apply it to the text areas Text component as thus...

((AbstractDocument)field.getDocument()).setDocumentFilter(...)
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366