1 package org.columba.core.gui.base; 2 3 import java.awt.Color ; 4 import java.util.regex.Matcher ; 5 import java.util.regex.Pattern ; 6 7 import javax.swing.text.AttributeSet ; 8 import javax.swing.text.BadLocationException ; 9 import javax.swing.text.SimpleAttributeSet ; 10 import javax.swing.text.StyleConstants ; 11 12 public class HighlighterDocument extends UndoDocument { 13 14 15 public void highlightInitialText(int length) { 16 SimpleAttributeSet gray = new SimpleAttributeSet (); 17 StyleConstants.setForeground(gray, Color.GRAY); 18 setCharacterAttributes(0, length, gray, true); 19 } 20 21 public void insertString(int offs, String str, AttributeSet a) 22 throws BadLocationException { 23 24 super.insertString(offs, str, a); 25 26 String s = getText(0,getLength()); 27 highlightText(s); 28 } 29 30 public void remove(int offs,int len) 31 throws BadLocationException { 32 33 super.remove(offs, len); 34 35 String s = getText(0,getLength()); 36 highlightText(s); 37 } 38 39 public void highlightText(String str) { 40 41 String EMailRegex = "([a-zA-Z0-9]+([_+\\.-][a-zA-Z0-9]+)*@([a-zA-Z0-9]+([\\.-][a-zA-Z0-9]+)*)+\\.[a-zA-Z]{2,4})"; 42 String URLRegex = "(\\b((\\w*(:\\S*)?@)?(http|https|ftp)://[\\S]+)(?=\\s|$))"; 43 String regex = EMailRegex + "|" + URLRegex; 44 Pattern EMailPat = Pattern.compile(regex); 45 Matcher EMailMatcher = EMailPat.matcher(str); 46 47 SimpleAttributeSet standard = new SimpleAttributeSet (); 48 49 SimpleAttributeSet highlighted = new SimpleAttributeSet (); 50 StyleConstants.setForeground(highlighted, Color.BLUE); 51 StyleConstants.setUnderline(highlighted, true); 52 53 int begin = 0; 54 int end; 55 while (EMailMatcher.find()) { 56 end = EMailMatcher.start(); 57 if (end > 1) 58 setCharacterAttributes(begin, end - begin, standard, true); 59 60 begin = end; 61 end = EMailMatcher.end(); 62 setCharacterAttributes(begin, end - begin, highlighted, true); 63 begin = end; 64 } 65 setCharacterAttributes(begin, str.length(), standard, true); 66 } 67 } 68 | Popular Tags |