问题
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);
}
回答1:
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);
回答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(...)
来源:https://stackoverflow.com/questions/11485505/limit-jtextpane-space-usage