每次键入密钥时,我都会得到 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。如何解决?