[英]How do I change color of every word in JTextPane?
每次键入键时,我都会得到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。 怎么解决呢?
您可以在JTextPane中使用HTML。 阅读有关它。
您忘记了单词之间的间隔:
//lastIndex += codeWords[a].length();
lastIndex += codeWords[a].length() +1;
当然,这假设只有一个空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.