Doing the Highlights
Now that we know the position of the first (openParen) and last (closeParen) characters we want to highlight, we can call the highlighter to actually highlight them.
Suppose that closeParen really is a closing parenthesis and openParen really matches it. (We'll consider other cases in a moment.) We can find the highlighter from the JTextComponent and highlight them:
highlighter = source.getHighlighter(); start = highlighter.addHighlight(openParen, openParen+1, goodPainter); end = highlighter.addHighlight(closeParen, closeParen+1, goodPainter);
Each highlight is one character long, starting at closeParen and openParen. We store the object returned in a field of the BracketMatcher because we're going to need to clear them later on when the caret moves. That's accomplished by the method clearHighlights:
public void clearHighlights() { if(highlighter != null) { if(start != null) highlighter.removeHighlight(start); if(end != null) highlighter.removeHighlight(end); start = end = null; highlighter = null; } }
We call clearHighlights every time the caret moves. The value of start could be null, if we couldn't find a matching opening parenthesis. When that happens, findMatchingParen returns 1 as the position, and the code looks like this:
if(openParen == -1) { end = highlighter.addHighlight(closeParen, closeParen+1, badPainter); }
There is one more case we're interested in, where there are both opening and closing parentheses, but they're of different types (such as ( and }). We'll use a badPainter for that case too. The details are left for the reader.
The complete code can be found here.