Below is a rough DocumentFilter that seems to work. His basic approach is to allow you to insert / add an event, request the number of rows after the fact, if it is greater than max, delete the rows from the very beginning, if necessary.
Beware: lines counted using textArea methods are (most likely, awaiting confirmation from @Stani) strings-between-cr, not the actual strings as layout. Depending on your exact requirement, they may or may not group you (if not, use the Stan utility methods)
I was surprised and not quite sure if he was safe.
- surprised: the insert method is not called, which is necessary to implement the replacement method instead (in the finished ready-made code, both are possible)
- I'm not sure that in text mode the guaranteed values will be returned in the filtering methods (maybe not, then the length check can be completed in invokeLater).
Some codes:
public class MyDocumentFilter extends DocumentFilter { private JTextArea area; private int max; public MyDocumentFilter(JTextArea area, int max) { this.area = area; this.max = max; } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { super.replace(fb, offset, length, text, attrs); int lines = area.getLineCount(); if (lines > max) { int linesToRemove = lines - max -1; int lengthToRemove = area.getLineStartOffset(linesToRemove); remove(fb, 0, lengthToRemove); } } }
kleopatra
source share