1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| ((AbstractDocument)editor.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset,
String text, AttributeSet attr)
throws BadLocationException {
StyledDocument doc = (StyledDocument) fb.getDocument();
StringBuilder sb = new StringBuilder(doc.getText(0, doc.getLength()));
sb.insert(offset, text);
applyChanges(fb, doc, sb, offset+text.length());
//super.insertString(fb, offset, text, null);
//applyChanges((StyledDocument) fb.getDocument());
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
StyledDocument doc = (StyledDocument) fb.getDocument();
StringBuilder sb = new StringBuilder(doc.getText(0, doc.getLength()));
sb.replace(offset, offset+length, "");
applyChanges(fb, doc, sb, offset); //
//super.remove(fb, offset, length);
//applyChanges((StyledDocument) fb.getDocument());
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs)
throws BadLocationException {
StyledDocument doc = (StyledDocument) fb.getDocument();
StringBuilder sb = new StringBuilder(doc.getText(0, doc.getLength()));
sb.replace(offset, offset+length, text);
applyChanges(fb, doc, sb, offset+text.length() );
//super.replace(fb, offset, length, text, null);
//applyChanges((StyledDocument) fb.getDocument());
}
private void applyChanges(FilterBypass fb, StyledDocument doc,
StringBuilder sb, int caretOffset) throws BadLocationException {
fb.remove(0, doc.getLength());
fb.insertString(0, sb.toString(), null);
editor.setCaretPosition(caretOffset);
applyChanges(doc);
}
private void applyChanges(StyledDocument doc) throws BadLocationException {
String wholetext = doc.getText(0,doc.getLength());
List<Token> tokens = parse(wholetext) ;
int offset=0;
for(Token token : tokens) {
setAttributes(doc, offset, token.length());
offset+=token.length();
}
}
}); |
Partager