我正在使用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);
}发布于 2012-07-15 00:55:51
当StyledDocument的长度超过一定的限制时,您可以从其开头删除等量的值:
int docLengthMaximum = 10000;
if(doc.getLength() + str.length() > docLengthMaximum) {
doc.remove(0, str.length());
}
doc.insertString(doc.getLength(), str, style);发布于 2012-07-15 01:10:47
您将希望利用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的字符限制过滤器
您需要将其应用于文本区域文本组件,如下所示...
((AbstractDocument)field.getDocument()).setDocumentFilter(...)https://stackoverflow.com/questions/11485505
复制相似问题