我有一個Java(Swing)數據記錄應用程序將文本寫入JScrollPane
中的JTextArea
。應用程序將文本附加到JTextArea
,並相應地向上滾動。在可視區域中只有5行文本,如果用戶只能向後滾動100行左右,這是可以接受的,但在我看來,消耗的內存量將繼續增長而沒有限制。內存使用Java JScrollPane
有什麼我可以做的,以限制保留的行數或限制使用的內存量?
我有一個Java(Swing)數據記錄應用程序將文本寫入JScrollPane
中的JTextArea
。應用程序將文本附加到JTextArea
,並相應地向上滾動。在可視區域中只有5行文本,如果用戶只能向後滾動100行左右,這是可以接受的,但在我看來,消耗的內存量將繼續增長而沒有限制。內存使用Java JScrollPane
有什麼我可以做的,以限制保留的行數或限制使用的內存量?
滾動窗格與此無關。您可以限制由JTextArea使用的PlainDocument保存的數據。我認爲一個DocumentFilter可以用於這個目的。
編輯1
這裏是camickr的代碼簡單的DocumentFilter版本(羅布:很抱歉的徹頭徹尾的偷竊)。
import javax.swing.text.*;
public class LimitLinesDocumentFilter extends DocumentFilter {
private int maxLineCount;
public LimitLinesDocumentFilter(int maxLineCount) {
this.maxLineCount = maxLineCount;
}
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, string, attr);
removeFromStart(fb);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
super.replace(fb, offset, length, text, attrs);
removeFromStart(fb);
}
private void removeFromStart(FilterBypass fb) {
Document doc = fb.getDocument();
Element root = doc.getDefaultRootElement();
while (root.getElementCount() > maxLineCount) {
removeLineFromStart(doc, root);
}
}
private void removeLineFromStart(Document document, Element root) {
Element line = root.getElement(0);
int end = line.getEndOffset();
try {
document.remove(0, end);
} catch (BadLocationException ble) {
ble.printStackTrace();
}
}
}
和代碼來測試它:
import javax.swing.*;
import javax.swing.text.PlainDocument;
public class LimitLinesDocumentFilterTest {
private static void createAndShowUI() {
int rows = 10;
int cols = 30;
JTextArea textarea = new JTextArea(rows , cols);
PlainDocument doc = (PlainDocument)textarea.getDocument();
int maxLineCount = 9;
doc.setDocumentFilter(new LimitLinesDocumentFilter(maxLineCount));
JFrame frame = new JFrame("Limit Lines Document Filter Test");
frame.getContentPane().add(new JScrollPane(textarea));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
有什麼我可以做,以限制行數保留
@camickr:Rob,對不起你的代碼徹底失竊!/Pete –
@SteveJP:使用DocumentFilter的缺點是每個Document只能有一個過濾器(據我所知)。 –
+1,皮特,沒問題,這是什麼樣的例子,建議/嘗試不同的方法。是的,文檔只能有一個過濾器。在「鏈接文檔過濾器」(http://tips4java.wordpress.com/2009/10/18/chaining-document-filters/)中,我試圖解決這個問題。 – camickr