How To Use Highlighters in JTextComponents
Project: Syntax Highlighting
Java provides an incredibly sophisticated extensible text-editing system via its JTextComponent and Document classes. These are, respectively, the controller and model of a model/view/controller pattern. For plain documents, such as JTextField and JTextArea, the controller is also the view. For styled components that allow formatting, such as JEditorPane, there is a separate view portion, not surprisingly called View (in the java.swing.text package), but it's really complicated. So we'll start with something a bit simpler: highlighting.
We'll demonstrate it with a component that highlights matching parentheses, braces, or brackets (I'll call them all "parentheses" here for simplicity), similar to the parenthesis matcher in Emacs. Whenever you put your cursor next to a closing parenthesis, it highlights both that character and the matching parenthesis. If they match correctly, it uses a soothing cyan (see Figure 1); if they don't, it uses a warning magenta. This is incredibly handy for a language like Java or C, to help ensure that your parentheses match properly, and spot the error if they don't. It's absolutely critical in a language like Lisp, which scatters parentheses around the way Java and C scatter semicolons.
Figure 1 Emacs parenthesis matching.
This article is about the Java text components, not about parsing, so I'm not going to take into account quotes or comments. Parsing those out without spending a long time at it (remember, we're trying to fit the highlighting in between keystrokes) is a challenge for another day.