KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > columba > core > gui > base > HighlighterDocument


1 package org.columba.core.gui.base;
2
3 import java.awt.Color JavaDoc;
4 import java.util.regex.Matcher JavaDoc;
5 import java.util.regex.Pattern JavaDoc;
6
7 import javax.swing.text.AttributeSet JavaDoc;
8 import javax.swing.text.BadLocationException JavaDoc;
9 import javax.swing.text.SimpleAttributeSet JavaDoc;
10 import javax.swing.text.StyleConstants JavaDoc;
11
12 public class HighlighterDocument extends UndoDocument {
13     
14     /* CEDRIC: not used right now. */
15     public void highlightInitialText(int length) {
16         SimpleAttributeSet JavaDoc gray = new SimpleAttributeSet JavaDoc();
17         StyleConstants.setForeground(gray, Color.GRAY);
18         setCharacterAttributes(0, length, gray, true);
19     }
20
21     public void insertString(int offs, String JavaDoc str, AttributeSet JavaDoc a)
22         throws BadLocationException JavaDoc {
23         
24         super.insertString(offs, str, a);
25         
26         String JavaDoc s = getText(0,getLength());
27         highlightText(s);
28     }
29     
30     public void remove(int offs,int len)
31      throws BadLocationException JavaDoc {
32         
33         super.remove(offs, len);
34         
35         String JavaDoc s = getText(0,getLength());
36         highlightText(s);
37     }
38     
39     public void highlightText(String JavaDoc str) {
40         
41         String JavaDoc EMailRegex = "([a-zA-Z0-9]+([_+\\.-][a-zA-Z0-9]+)*@([a-zA-Z0-9]+([\\.-][a-zA-Z0-9]+)*)+\\.[a-zA-Z]{2,4})";
42         String JavaDoc URLRegex = "(\\b((\\w*(:\\S*)?@)?(http|https|ftp)://[\\S]+)(?=\\s|$))";
43         String JavaDoc regex = EMailRegex + "|" + URLRegex;
44         Pattern JavaDoc EMailPat = Pattern.compile(regex);
45         Matcher JavaDoc EMailMatcher = EMailPat.matcher(str);
46         
47         SimpleAttributeSet JavaDoc standard = new SimpleAttributeSet JavaDoc();
48         
49         SimpleAttributeSet JavaDoc highlighted = new SimpleAttributeSet JavaDoc();
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