首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >限制JTextPane空间使用

限制JTextPane空间使用
EN

Stack Overflow用户
提问于 2012-07-15 00:38:46
回答 2查看 1K关注 0票数 2

我正在使用JTextPane来记录来自网络应用程序的一些数据,在程序运行了大约10个小时之后,我得到了内存堆错误。文本不断地添加到JTextPane中,这就不断增加了内存使用量。有没有什么方法可以让JTextPane像命令提示符窗口一样工作?当新文本进入时,我应该删除旧文本吗?这是我用来写入JTextPane的方法。

代码语言:javascript
复制
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);
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-15 00:55:51

当StyledDocument的长度超过一定的限制时,您可以从其开头删除等量的值:

代码语言:javascript
复制
int docLengthMaximum = 10000;
if(doc.getLength() + str.length() > docLengthMaximum) {
    doc.remove(0, str.length());
}
doc.insertString(doc.getLength(), str, style);
票数 3
EN

Stack Overflow用户

发布于 2012-07-15 01:10:47

您将希望利用Documents DocumentFilter

代码语言:javascript
复制
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的字符限制过滤器

您需要将其应用于文本区域文本组件,如下所示...

代码语言:javascript
复制
((AbstractDocument)field.getDocument()).setDocumentFilter(...)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11485505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档