【发布时间】:2015-09-06 01:46:01
【问题描述】:
我在为 JTextPane 中的某些关键字着色时遇到问题。换句话说,我想制作一个迷你 IDE 之类的东西,所以我会编写一些代码,并且我想为“public”“private”等关键字赋予颜色(比如蓝色)。问题是它非常慢!因为每次我点击“空格”或“退格”键时,该函数都会扫描整个文本以为关键字提供颜色,所以当我在文本窗格中编写大量代码时,它会变得非常慢。 这是我匹配关键字的功能:
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;
}
}
这是我为匹配的单词着色的功能:
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);
}
提前致谢 =)
【问题讨论】:
-
无需检查整个文本,只需更改行,
标签: java swing colors jtextpane