[英]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.