每次键入键时,我都会获得jpane的字符,使用空格分割它们并为其他(随机)颜色的每个单词着色。这段代码完成了工作:
private class KeyHandler extends KeyAdapter {
@Override
public void keyPressed(KeyEvent ev) {
String[] codeWords = codePane.getText().split("\\s");
StyledDocument doc = codePane.getStyledDocument();
SimpleAttributeSet set = new SimpleAttributeSet();
int lastIndex = 0;
for (int a = 0; a < codeWords.length; a++) {
Random random = new Random();
StyleConstants.setForeground(set, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
doc.setCharacterAttributes(lastIndex, codeWords[a].length(), set, true);
lastIndex += codeWords[a].length();
}
}
}
问题是它改变了jpane文本中的每一个字符,而不是每个WORD。怎么解决?
答案 0 :(得分:0)
您可以在JTextPane中使用HTML。阅读它。
答案 1 :(得分:0)
你忘记了单词之间的空格:
//lastIndex += codeWords[a].length();
lastIndex += codeWords[a].length() +1;
当然这假设只有一个空格。