2

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);
}
4

2 に答える 2

3

その長さが特定の制限を超えると、StyledDocument の先頭から同等の量を削除できます。

int docLengthMaximum = 10000;
if(doc.getLength() + str.length() > docLengthMaximum) {
    doc.remove(0, str.length());
}
doc.insertString(doc.getLength(), str, style);
于 2012-07-14T16:55:50.837 に答える
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の文字制限フィルターに基づく

したがって、テキスト領域のテキストコンポーネントに適用する必要があります...

((AbstractDocument)field.getDocument()).setDocumentFilter(...)
于 2012-07-14T17:10:47.453 に答える