If you need to change the font, color, etc. of the text inside a JTextPane component you will basically need to follow the next steps:

Where offset represents the starting position where you are going to insert the color and length represents the length (starting from the offset) that you wish color.

In the following scenario I will show you how to “highlight” the java keywords in a given text. To identify the keywords we will use Regular Expressions.


First we will have to a default color for text highlighting and blue is my color of choice.

The second step will be to define a regular expression that contains all the Java Keywords. For simplicity I chose to use static variables “attached” to my GUI class:

The resulting string (JAVA_KEYWORDS_REGEX) will look like this (something that it’s not advisable to write by hand):

For designing the GUI I’ve used an Eclipse plugin called WindowBuilder, and my component hierarchy looks like this:


The functions that are modifying the text are:

And the action behind the button is: Continue reading