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:

Full sourcecode:

One thought on “How to customize the font inside a JTextPane component (Java Swing) – Highlight Java Keywords inside a JTextPane

  1. A third team which fun to look when in Prague is FK Victoria Zizkov.

    These people save few cents site works, due to appreciate them for
    their good behaviours. At regular price, these might have cost me $17.94.


Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url=""> 


Are we human, or are we dancer *