0

Every time key is typed i get jpane's characters, split them using spaces and color every word in other (random) color. This fragment of code does the work:

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();
            }
        }
    }

The problem is that it changes EVERY char of jpane's text, not every WORD. How to solve it?

user2102972
  • 251
  • 2
  • 6
  • 13
  • Give a look at http://stackoverflow.com/questions/6068398/how-to-add-text-different-color-on-jtextpane – araknoid Mar 02 '13 at 13:32

2 Answers2

0

You can use HTML inside JTextPane. read about it.

Shelef
  • 3,707
  • 6
  • 23
  • 28
0

You forgot about the space between words:

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

of course this assumes there is only a single space.

camickr
  • 321,443
  • 19
  • 166
  • 288