• category: swing folder: FIFODocument title: JTextAreaに表示できる行数を制限 tags: [JTextArea, DocumentListener] author: aterai pubdate: 2006-02-27T11:11:21+09:00 description: ドキュメントのサイズを一定にして、JTextAreaなど表示できる行数を制限します。 image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTMafjL8xI/AAAAAAAAAZI/-KMSGPcn0jM/s800/FIFODocument.png

概要

概要

ドキュメントのサイズを一定にして、JTextAreaなど表示できる行数を制限します。Swing (Archive) - JTextArea Memory Overflow ??にあるソースコードを参考にしています。

サンプルコード

サンプルコード

jta.setEditable(false);
jta.getDocument().addDocumentListener(new DocumentListener() {
  @Override public void insertUpdate(DocumentEvent e) {
    final Document doc = jta.getDocument();
    final Element root = doc.getDefaultRootElement();
    if (root.getElementCount() <= maxLines) return;
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        removeLines(doc, root);
      }
    });
    jta.setCaretPosition(doc.getLength());
  }
#spanadd

#spanend
  private void removeLines(Document doc, Element root) {
    Element fl = root.getElement(0);
    try {
      doc.remove(0, fl.getEndOffset());
    } catch (BadLocationException ble) {
      System.out.println(ble);
    }
  }
#spanadd

#spanend
  @Override public void removeUpdate(DocumentEvent e) {}
#spanadd

#spanend
  @Override public void changedUpdate(DocumentEvent e) {}
});
#spandel
final Timer timer = new Timer(100, new ActionListener() {
#spanend
  @Override public void actionPerformed(ActionEvent e) {
    String s = new Date().toString();
    jta.append((jta.getDocument().getLength() > 0) ? "\n" + s : s);
  }
#spanadd
Timer timer = new Timer(100, () -> {
#spanend
  String s = new Date().toString();
  jta.append((jta.getDocument().getLength() > 0) ? "\n" + s : s);
});
View in GitHub: Java, Kotlin

解説

一行追加された時に、規定の行数を越えている場合は、先頭から一行を削除しています。

解説

上記のサンプルでは、1行追加した時に規定の行数を越えている場合、先頭の1行を削除するDocumentListenerを作成し、これをJTextAreaに設定しています。 上記のサンプルでは、10行以上になると先頭行から削除されていきます。また、複数行の入力やペーストには対応していません。それらにも対応する場合は、Swing (Archive) - JTextArea Memory Overflow ??を参考にしてみてください。
  • 10行以上になると先頭行から削除
  • 複数行テキストのペーストには未対応
  • DocumentListenerではなく以下のようなDocumentFilterを設定する方法もある
    #spanend
    #spanadd
    ((AbstractDocument) ta.getDocument()).setDocumentFilter(new FIFODocumentFilter());
    #spanend
    #spanadd
    // ...
    #spanend
    #spanadd
    class FIFODocumentFilter extends DocumentFilter {
    #spanend
      private static final int MAX_LINES = 10;
      @Override public void insertString(
          DocumentFilter.FilterBypass fb, int offset,
          String string, AttributeSet attr)
          throws BadLocationException {
        fb.insertString(offset, string, attr);
        Element root = fb.getDocument().getDefaultRootElement();
        if (root.getElementCount() > MAX_LINES) {
          fb.remove(0, root.getElement(0).getEndOffset());
        }
      }
    #spanadd
    }
    #spanend
    #spanadd
    

参考リンク

参考リンク

コメント

コメント