I have a small working text editor written in Java using JTextPane and I would like to color specific words. It would work in the same fashion that keywords in Java (within Eclipse) are colored; if they are a keyword, they are highlighted after the user is done typing them. I am new to text editors implemented in Java, any ideas?
-
This is quite a complex task, if you can find a 3rd party library, that would greatly simplify the problems. Having said that, you could take a look at [this example](http://stackoverflow.com/questions/19399904/set-hilighting-color-in-jtextfield/19401765#19401765) and [this example](http://stackoverflow.com/questions/14727548/java-change-the-document-in-documentlistener/14727657#14727657) if you really wanted to try your hand at it... – MadProgrammer Oct 20 '13 at 08:18
-
@MadProgrammer Don't make it complex. Use `JSyntaxPane` instead ;-) I know you are a simple person. :-P – An SO User Oct 20 '13 at 08:31
-
@LittleChild It's not about me, it's what the OP wants ;) – MadProgrammer Oct 20 '13 at 09:00
-
@MadProgrammer Make it easy for everyone ?? :P – An SO User Oct 20 '13 at 09:02
-
1@LittleChild The OP may not be to use 3rd party libraries so demonstrating a single choice may actually be a bad choice. Besides, once the realise the complexity of the task, they may actually decide a 3rd party library is what they need. – MadProgrammer Oct 20 '13 at 09:05
-
@MadProgrammer I actually did highlight the complexity :D – An SO User Oct 20 '13 at 09:13
1 Answers
In computer science, lexical analysis is the process of converting a sequence of characters into a sequence of tokens. A program or function that performs lexical analysis is called a lexical analyzer, lexer, tokenizer,[1] or scanner. A lexer often exists as a single function which is called by a parser or another function, or can be combined with the parser in scannerless parsing.
Having said that, it is no trivial task. You need a high level library to do that. It will ease your task. What is the way out ?
Use ANTLR. Here is what its site says:
ANTLR is a powerful parser generator that you can use to read, process, execute, or translate structured text or binary files. It’s widely used in academia and industry to build all sorts of languages, tools, and frameworks....
NetBeans IDE parses C++ with ANTLR.
There, problem solved. The author of ANTLR also has a book on how to use ANTLR which you may want to buy if you wanna learn how to use it.
Having given you enough brain melt, there is an out of the box solution available for you: JSyntaxPane. Just like any JCOmponent, you initialize it and pop it into a JFrame. It works like a charm. It supports a whole lot of languages apart from Java

- 24,612
- 35
- 133
- 221