日期:2014-05-20  浏览次数:20887 次

java 高手请进
import java.util.regex.*;
import javax.swing.*;

import java.awt.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.event.*;

public class Regex extends JFrame{
private JTextPane textPane = new JTextPane();
private SimpleAttributeSet attribute = new SimpleAttributeSet();
private StyledDocument doc = textPane.getStyledDocument();
private int start = 0;
private int end;
private String str;
Pattern pt = Pattern.compile("int");

public Regex(){
add(textPane);
setSize(560,392);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

//add event
StyleConstants.setForeground(attribute,Color.RED);
doc.addDocumentListener(new DocumentListener(){

public void insertUpdate(DocumentEvent arg0) {

Matcher mc = pt.matcher(textPane.getText());
while(mc.find()){
start = mc.start();
end = mc.end();
doc.setCharacterAttributes(start,end,attribute,true);
}

}

public void removeUpdate(DocumentEvent arg0) {


}

public void changedUpdate(DocumentEvent arg0) {


}

});


}

public static void main(String[] args){
new Regex();
}

}
上面这段程序的功能是: 当在textPane 中写“int”是,字体会自动变成红色,可运行是出现了错误,怎么也找不到
原因,哪位高手能帮我解决,谢了!

------解决方案--------------------
Java code

package pdm.servlet;

import java.util.regex.*;
import javax.swing.*;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.text.*;
import javax.swing.event.*;

public class Test extends JFrame {
   private JTextPane textPane = new JTextPane();
   
   private SimpleAttributeSet attribute = new SimpleAttributeSet();
   
   private StyledDocument doc = textPane.getStyledDocument();
   
   Pattern pt = Pattern.compile("int");
   
   public Test() {
      add(textPane);
      setSize(560, 392);
      setResizable(false);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
      // add event
      StyleConstants.setForeground(attribute, Color.RED);
      textPane.addKeyListener(new KeyAdapter() {
         public void keyReleased(KeyEvent arg0) {
            Matcher mc = pt.matcher(textPane.getText());
            System.err.println(textPane.getText());
            while(mc.find()) {
               doc.setCharacterAttributes(mc.start(), mc.end() - mc.start(), attribute, true);
            }
         }
      });
   }
   
   public static void main(String[] args) {
      new Test();
   }
   
}