如何给JTextPane的内容进行特殊关键字修饰(如用不同的颜色表示)

       相信不少人写过关于文本编辑器的程序,或者正在写各类程序。也许你正在为其中的某些问题而烦恼,如怎样对关键字进行修饰就曾经烦扰了我很久,现在已经解决了这个问题,下面就把我解决的方法给大家分享一下吧:

首先要说明的是要对关键字进行修饰必须用JTextPane类

//第一个类:数据类:WrodNode.java
package eu.jxau.presubmit;
/**
 * 装有单词和单词所在位置的数据结构
 * @author Sunly
 *
 */
public class WordNode {
 private int location;
 private String word;
 public WordNode(int location, String str) {
  super();
  this.location = location;
  this.word = str;
 }
 public int getLocation() {
  return location;
 }
 public String getWord() {
  return word;
 }
 
}
 
//第二个类:修饰类:DecorateKeyWords.java
package eu.jxau.presubmit;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JTextPane;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class DecorateKeyWords {
 private static URL keywordsRul = CodeFile.class
   .getResource("/Documents/javaKeyWords.xml");
 private static File f = new File(keywordsRul.getFile());
 private static String keyWords[];
 private JTextPane tp;
 /**
  * 构造函数
  */
 public DecorateKeyWords() {
  keyWords = getKeyWords(f); //这只是一个我自己写的从文件中读取关键字的方法,你也可以直接定义
  //如:keyWords[] = {"class", "public"};
 }
 /**
  * 返回一组根据字符顺序排序好的字符串数组
  * 
  * @param file 存放关键字的文件
  * @return 排好序的字符串
  */
 public static String[] getKeyWords(File file) {
  String[] strs = null;
  SAXBuilder builder = new SAXBuilder();
  try {
   Document doc = builder.build(file);
   Element root = doc.getRootElement();
   List list = root.getChildren("key");
   int length = list.size();
   strs = new String[length];
   for (int i = 0; i < length; i++) {
    Element e = (Element) list.get(i);// Circlue
    strs[i] = e.getTextTrim();
   }
   sort(strs); // 对返回的字符串数组根据字符顺序排序
  } catch (JDOMException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return strs;
 }
 /**
  *对JTextPane里面内容的关键字进行修饰
  * @param tp JTextPane按钮
  */
 public void decorateKeyWords(JTextPane tp) {
  // 对所有关键词进行修饰颜色
  String text = tp.getText();
  StyledDocument doc = tp.getStyledDocument();
  SimpleAttributeSet attribute1 = new SimpleAttributeSet();
  StyleConstants.setForeground(attribute1, Color.cyan);
  ListIterator<WordNode> iterator1 = split2(text, ' ', '{', '}', '(', ')',
    '<', '>', '.', '\n');
  while (iterator1.hasNext()) {
   WordNode wn = iterator1.next();
   // System.out.println(wn.getWord());
   if (isKeyWords(keyWords, wn.getWord())) {
    System.out.println("location:" + wn.getLocation() + "\t"
      + "Str:" + wn.getWord() + "\tlen:"
      + wn.getWord().length());
    doc.setCharacterAttributes(wn.getLocation(), wn.getWord()
      .length(), attribute1, true);
   }
  }
  // 对注释行进行修饰不同的颜色
  SimpleAttributeSet attribute2 = new SimpleAttributeSet();
  StyleConstants.setForeground(attribute2, Color.green);
  ListIterator<WordNode> iterator2 = split2(text, '\n');
  boolean exegesis = false; // 是否加了/*的注释
  while (iterator2.hasNext()) {
   WordNode wn = iterator2.next();
   if (wn.getWord().startsWith("//")) {
    doc.setCharacterAttributes(wn.getLocation(), wn.getWord()
      .length(), attribute2, true);
   } else if (wn.getWord().startsWith("/*")
     && wn.getWord().endsWith("*/")) {
    doc.setCharacterAttributes(wn.getLocation(), wn.getWord()
      .length(), attribute2, true);
   } else if (wn.getWord().startsWith("/*")
     && !wn.getWord().endsWith("*/")) {
    exegesis = true;
    doc.setCharacterAttributes(wn.getLocation(), wn.getWord()
      .length(), attribute2, true);
   } else if (!wn.getWord().startsWith("/*")
     && wn.getWord().endsWith("*/") && true == exegesis) {
    doc.setCharacterAttributes(wn.getLocation(), wn.getWord()
      .length(), attribute2, true);
    exegesis = false;
   } else if (true == exegesis) {
    doc.setCharacterAttributes(wn.getLocation(), wn.getWord()
      .length(), attribute2, true);
   }
  }
 }
 /**
  * 判断一个词是否为关键词
  * @param keyWords 关键词数组
  * @param s 要进行判断的关键词
  * @return 如果是关键词则返回true,否则返回false
  */
 private static boolean isKeyWords(String[] keyWords, String s) {
  int low = 0, high = keyWords.length - 1;
  while (low <= high) {
   int mid = (low + high) / 2;
   if (s.equals(keyWords[mid])) {
    return true;
   } else if (s.compareTo(keyWords[mid]) < 0) {
    high = mid - 1;
   } else {
    low = mid + 1;
   }
  }
  /*
   * for(int i=0; i<keyWords.length; i++) { if(s.equals(keyWords[i])) {
   * return true; } }
   */
  return false;
 }
 /**
  * 按照指定的多个字符进行字符串分割,如‘ ’或‘,’等
  * @param str 
  *            被分割的字符串
  * @param regexs
  *            要分割所需的符号
  * @return 分割后的字符串数组
  */
 public static String[] split(String str, char... regexs) {
  StringBuilder strBuilder = new StringBuilder();
  for (int i = 0; i < regexs.length; i++) {
   if (i == regexs.length - 1) {
    strBuilder.append("[").append(regexs[i]).append("]");
   } else {
    strBuilder.append("[").append(regexs[i]).append("]|");
   }
  }
  Pattern p = Pattern.compile(strBuilder.toString());
  Matcher m = p.matcher(str);
  List<String> strList = new ArrayList();
  int strStart = 0; // 分割单词的首位置
  String s; // 分割的单词
  while (m.find()) {
   s = str.substring(strStart, m.start());
   if (!s.equals(new String())) {
    strList.add(s.trim());
   }
   strStart = m.start() + 1;
  }
  s = str.substring(strStart, str.length());
  strList.add(s);
  String strs[] = new String[strList.size()];
  return strList.toArray(strs);
 }
 /**
   * 按照指定的多个字符进行字符串分割,如‘ ’或‘,’等
  * @param str 
  *            被分割的字符串
  * @param regexs
  *            要分割所需的符号
  * @return 包含WordNodeList对象的iterator
  */
 public ListIterator<WordNode> split2(String str, char... regexs) {
  StringBuilder strBuilder = new StringBuilder();
  for (int i = 0; i < regexs.length; i++) {
   if (i == regexs.length - 1) {
    strBuilder.append("[").append(regexs[i]).append("]");
   } else {
    strBuilder.append("[").append(regexs[i]).append("]|");
   }
  }
  Pattern p = Pattern.compile(strBuilder.toString());
  Matcher m = p.matcher(str);
  List<WordNode> nodeList = new ArrayList();
  int strStart = 0; // 分割单词的首位置
  String s; // 分割的单词
  WordNode sn; // StringNode节点
  while (m.find()) {
   s = str.substring(strStart, m.start());
   if (!s.equals(new String())) {
    sn = new WordNode(strStart, s);
    nodeList.add(sn);
   }
   strStart = m.start() + 1;
  }
  s = str.substring(strStart, str.length());
  sn = new WordNode(strStart, s);
  nodeList.add(sn);
  return nodeList.listIterator();
 }
 /**
  * 按字符表顺序对字符串进行冒泡排序
  * @param strs 要排序的字符串
  */
 public static void sort(String[] strs) {
  // int n = r.length;
  for (int i = 0; i < strs.length; i++) {
   for (int j = 0; j < strs.length - i - 1; j++) {
    if (strs[j].compareTo(strs[j + 1]) > 0) {
     String temp = strs[j];
     strs[j] = strs[j + 1];
     strs[j + 1] = temp;
    }
   }
  }
 }
 /*
 public static void main(String[] args) {
  String strs[] = split("jdjdj jdie java", ' ');
  for(int i=0; i<strs.length; i++) {
   System.out.println(strs[i]);
  }
 }*/
}
 
 
 
//第三个类,测试类 TextPane.java
package eu.jxau.presubmit;
import javax.swing.JFrame;
import javax.swing.JTextPane;
public class TextPane extends JFrame{
 JTextPane tp = new JTextPane();
 public TextPane() {
  String fileStr = "class Test extends JFrame{" + "\n" +
  "//public Test() {" + "\n" +
  "/*this.getContentPane().add(codes.getShowCodesPanel());" +"\n" +
  "this.setBounds(300,100,800,600);*/" + "\n" +
  "new Test();";
  tp.setText(fileStr);
  this.add(tp);
  DecorateKeyWords dc = new DecorateKeyWords();
  
  this.setBounds(300, 200, 400, 300);
  this.setVisible(true);
  dc.decorateKeyWords(tp);
 }
 /**
  * @param args
  */
 public static void main(String[] args) {
  new TextPane();
 }
}


 

你可能感兴趣的:(数据结构,String,File,iterator,Class,文本编辑)