JTextPane Space Usage Limit

I use JTextPane to register some data from a network application, and after the program runs for more than 10 hours or so, I get a memory heap error. Text continues to be added to JTextPane, which increases memory usage. Is there a way to make JTextPane act like a command line window? Should I get rid of the old text when new text appears? This is the method that I use to write to 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);
}
+2
source share
2 answers

You can remove the equivalent amount from the beginning of the StyledDocument if 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);
+3
source

Do you want to use Document 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);
    }
}

http://www.jroller.com/dpmihai/entry/documentfilter

...

((AbstractDocument)field.getDocument()).setDocumentFilter(...)
+2

Source: https://habr.com/ru/post/1693558/


All Articles