I have a problem regarding coloring some keywords in a JTextPane. In other words, I want to make something like a mini IDE so I will write some code and I want to give a color (say blue) for some keywords like "public" "private" ... etc. The problem is that it is strongly slow !! as each time I hit the "space" or "backspace" key the function scans the whole text to give a color to the keywords, so when I write a lot of code in the textpane it gets very slow. here is my function of matching keywords:
public void matchWord() throws BadLocationException {
String tokens[] = ArabicParser.tokenNames;
int index = 0;
String textStr[] = textPane.getText().split("\\r?\\n");
for(int i=0 ; i<textStr.length ; i++) {
String t = textStr[i];
StringTokenizer ts2 = new StringTokenizer(t, " ");
while(ts2.hasMoreTokens()) {
String token = ts2.nextToken();
// The iterations are reduced by removing 16 symbols from the search space
for(int j = 3 ; j<tokens.length-5 ; j++) {
if(!(token.equals("؛")) && (tokens[j].equals("'"+token+"'"))) {
changeColor(textPane,token,Color.BLUE,index,token.length());
break;
} else {
changeColor(textPane,token,Color.BLACK,index,token.length());
}
}
index += token.length() + 1;
}
//index -= 1;
}
}
and here is my function of coloring the matched words:
private void changeColor(JTextPane tp, String msg, Color c, int beginIndex, int length) throws BadLocationException {
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setForeground(sas, c);
StyledDocument doc = (StyledDocument)tp.getDocument();
doc.setCharacterAttributes(beginIndex, length, sas, false);
sas = new SimpleAttributeSet();
StyleConstants.setForeground(sas, Color.BLACK);
tp.setCharacterAttributes(sas, false);
}
and thanks in advance =)