我正在使用JTextPane从网络应用程序记录一些数据,并且在程序运行大约10个多小时后,我得到了内存堆错误。文本继续添加到JTextPane,这会不断增加内存使用量。反正我是否可以使JTextPane像命令提示符窗口一样?当新文本出现时我应该摆脱旧文本吗?这是我用来写入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);
}
答案 0 :(得分:3)
一旦长度超过某个限制,您可以从StyledDocument的开头删除等值的数量:
int docLengthMaximum = 10000;
if(doc.getLength() + str.length() > docLengthMaximum) {
doc.remove(0, str.length());
}
doc.insertString(doc.getLength(), str, style);
答案 1 :(得分:2)
您需要利用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);
}
}
基于http://www.jroller.com/dpmihai/entry/documentfilter
的字符限制器过滤器您需要将其应用于文本区域Text组件,因此......
((AbstractDocument)field.getDocument()).setDocumentFilter(...)