File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Color specifics words in a JTextPane Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Color specifics words in a JTextPane" Watch "Color specifics words in a JTextPane" New topic

Color specifics words in a JTextPane

Antonio Ruffolo

Joined: Jun 28, 2011
Posts: 2
I want to color some words as soon as they are typed.
This is the code.

I use a Key_release listener.
When it catches the event i do this:
punt the text in a string
check that there is the word that I want to color
start to color it in a while(true) cycle, which ends when there aren't any other occurrences of the word.

My problem is that it doesn't color only the range that I specified, but al the rest of the text that i type will have that color.
For this reason wrote ne next two lines

The problem is, that in this way it colors only a word, I can't use it to color more different words.
If you try to run the code, it will color the word "prova", but if you remove the comments surrounding this if
It won't color the word ADD.

Do you have any idea of how to do this?
Rob Spoor

Joined: Oct 27, 2005
Posts: 20276

DocumentListener is a better choice than KeyListener, as it also will be triggered when pasting text.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Color specifics words in a JTextPane
jQuery in Action, 3rd edition