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 =)
Consider replacing
StringTokenizersince it's modern use is discoraged https://stackoverflow.com/a/6983908/1493294Consider refactoring
String tokens[]intoHashSet<String> tokens. Hash lookup will be faster than looping, especially astokens[]gets large.If you'd like to use more than two colors try
HashMap<String, Color> tokens.Also, having two very different things called
tokenandtokensrunning around in here is confusing. Consider renamingtokens[]tocoloredNames[]so it's clearly different than thetokenfrom thetextPanetokens.Consider using a profiler to see where the bulk of the time is being spent. You might find repetitive work being done in
changeColor()would be worth caching.If so write a class called
ColorChanger.ColorChangerwill have one constructor and one methodchangeColor(). The constructor will take (and thus cache) the parameters that don't change as you loop.ColorChanger.changeColor()will take the parameters that do change as you loop.