Take the 2-minute tour ×

I want to change the certain texts written on a JTextPane dynamically. I have a String array containing the words which should be changed

String ListMethod [] = {"forward", "backward", "left", "right"};

I've gone through some posts and many suggest to use JTextPane or JEditorPane to edit text but most of the answers given work on static text. I want to do it in a way such that as I type "forward" or "backward", etc... in the textpane, it detects this words and changes the color. How can I go about it?

Thanks for your help.

share|improve this question

2 Answers 2

See here how to implement a DocumentListener Value Change Listener to JTextField. The have a look at javax.swing.text.Highlighter and javax.swing.text.HighlightPainter.

share|improve this answer
Thanks for the links specially the one about DocumentListener. Seems like I'd have to use an event listener afterall. –  mkab Dec 19 '12 at 0:46

You have to capture the appropriate event and perform actions. For example in your case you can create an ActionListener that changes color and use registerKeyBoardAction to attach it on your JTextPane.

Oracle has a good tutorial: http://docs.oracle.com/javase/tutorial/uiswing/events/index.html on event listeners. I suggest you start getting yourself familiar there

share|improve this answer

Your Answer


