Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何更改JTextPane中每个单词的颜色?_Java_Jtextpane - Fatal编程技术网

Java 如何更改JTextPane中每个单词的颜色?

Java 如何更改JTextPane中每个单词的颜色?,java,jtextpane,Java,Jtextpane,每次键入键时,我都会得到jpane的字符,用空格分割它们,并用其他(随机)颜色给每个单词着色。这段代码完成以下工作: private class KeyHandler extends KeyAdapter { @Override public void keyPressed(KeyEvent ev) { String[] codeWords = codePane.getText().split("\\s"); St

每次键入键时,我都会得到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();
            }
        }
    }
私有类KeyHandler扩展了KeyAdapter{
@凌驾
按下公共无效键(KeyEvent ev){
字符串[]码字=codePane.getText().split(\\s”);
StyledDocument doc=codePane.getStyledDocument();
SimpleAttributeSet=新的SimpleAttributeSet();
int lastIndex=0;
for(int a=0;a

问题是它改变了jpane文本的每个字符,而不是每个单词。如何解决它?

您可以在JTextPane中使用HTML。读一读。

你忘了单词之间的空格:

//lastIndex += codeWords[a].length();
lastIndex += codeWords[a].length() +1;
当然,这是假设只有一个空格。

请查看