简体   繁体   中英

How do I change color of every word in JTextPane?

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?

You can use HTML inside JTextPane. read about it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM