【问题标题】:How do I change color of every word in JTextPane?如何更改 JTextPane 中每个单词的颜色?
【发布时间】:2013-03-02 13:11:07
【问题描述】:

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

【问题讨论】:

标签: java jtextpane


【解决方案1】:

您可以在 JTextPane 中使用 HTML。阅读它。

【讨论】:

    【解决方案2】:

    你忘了单词之间的空格:

    //lastIndex += codeWords[a].length();
    lastIndex += codeWords[a].length() +1;
    

    当然这是假设只有一个空格。

    【讨论】:

      猜你喜欢
      • 2013-01-02
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      • 2014-04-28
      • 2013-02-20
      相关资源
      最近更新 更多