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 =)
You could use a DocumentListener to analyse only the text that is inserted inside your TextPane. This way, you wouldn't need to analyse the whole text multiple times, you would check only what is added.
To do so, you would need to get the
getWordStart
andgetWordEnd
methods of the javax.swing.text.Utilities class. This way you can get the surrounding context of the insert location.Edit : Removing can change the state of the keywords. When you remove, you need to get the text between the removal start position and
getWordStart
, and the text between the removal end position andgetWordEnd
. For instance, if you remove "continental sur" from "intercontinental surface", you would get "interface" which might be a keyword.You could use this class for instance :