有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

与Java JScrollPane一起使用swing内存

我有一个Java(Swing)数据记录应用程序将文本写入JScrollPane中的JTextArea。应用程序将文本附加到JTextArea并相应地向上滚动。在可视区域中只有5行文本,如果用户只能向后滚动100行左右是可以接受的,但在我看来,消耗的内存量将继续无限增长

我能做些什么来限制保留的行数或限制使用的内存量


共 (2) 个答案

  1. # 2 楼答案

    滚动窗格与此无关。您可以限制JTextArea使用的PlainDocument所持有的数据。我认为DocumentFilter可以用于此目的

    编辑1
    这里有一个简单的camickr代码的文档过滤器版本(Rob:对彻头彻尾的盗窃感到抱歉!)

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