0
每次輸入密鑰,我都會得到jpane的字符,使用空格分隔它們,並以其他(隨機)顏色對每個單詞進行着色。這段代碼片段做的工作:如何更改JTextPane中每個單詞的顏色?
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文本的每一個字符,而不是每一個字。如何解決它?
看看http://stackoverflow.com/questions/6068398/how-to-add-text-different-color-on-jtextpane – araknoid 2013-03-02 13:32:33