Listing 1:
import com.sun.java.swing.*;
import com.sun.java.swing.text.*;
import java.util.*;
import java.awt.*;
public class CodeDocument extends DefaultStyledDocument{
private String word = "";
private SimpleAttributeSet bold =
new SimpleAttributeSet();
private SimpleAttributeSet normal
= new SimpleAttributeSet();
private int currentPos = 0;
private Vector keywords = new Vector();
public CodeDocument() {
//set the bold attribute
StyleConstants.setBold(bold,
true);
}
private void checkForKeyword(){
int offs = this.currentPos;
Element element = this.getParagraphElement(offs);
String elementText = "";
try{
//this gets
our chuck of current text for the element we’re on
elementText
= this.getText(element.getStartOffset(),
element.getEndOffset() - element.getStartOffset());
}
catch(Exception ex){
//whoops!
System.out.println("no
text");
}
int strLen = elementText.length();
if (strLen == 0) {return;}
int i = 0;
if (element.getStartOffset()
> 0){
//translates
backward if neccessary
offs = offs
- element.getStartOffset();
}
if ((offs >= 0) &&
(offs <= strLen-1)){
i = offs;
while (i >0){
//the while
loop walks back until we hit a delimiter
i--;
char charAt = elementText.charAt(i);
if ((charAt == ' ') | (i == 0) | (charAt =='(') | (charAt ==')') |
(charAt == '{') | (charAt == '}')){ //if i == 0 then we're at the begininng
if(i != 0){
i++;
}
word = elementText.substring(i, offs);//skip the period
String s = word.trim().toLowerCase();
//this is what actually checks for a matching keyword
if (keywords.contains(s)){
try{
//remove the old word and formatting
this.remove(currentPos - word.length(), word.length());
/*replace it with the same word, but new formatting
*we MUST call the super class insertString method here, otherwise we
*would end up in an infinite loop !!!!!*/
super.insertString(currentPos - word.length(), word, bold);
}
catch (Exception ex){
ex.printStackTrace();
}
}
break;
}
}
}
}
public void insertString(int offs,
String str,
AttributeSet a) throws BadLocationException{
if (offs < 0){
return;
}
currentPos = offs;
char strChar;
super.insertString(offs,
str, normal);
int strLen = str.length();
if (strLen > 1){
}
else{
strChar =
str.charAt(0);
switch (strChar){
case ('{'):case ('}'):case (' '): case('\n'):
case ('('):case (')'):case (';'):case ('.'):{
checkForKeyword();
wordStart = offs;
}
break;
}//end switch
}
}
public Vector getKeywords(){
return this.keywords;
}
public void setKeywords(Vector aKeywordList){
if (aKeywordList != null){
this.keywords
= aKeywordList;
}
}
}