Posted by Rob Camick on October 28, 2008
All text components allow you to highlight certain portions of text. This is done by adding a highlight to the Highlighter. The highlight will then use a HighlightPainter to paint the highlight. The default painter simply paints a coloured background. Effective but rather plain. Now is your chance to create a custom painter and jazz up the highlighting.
Lets start with a RectanglePainter. This was really easy because once you identify the actual code in the DefaultHighlighter.DefaultHighlightPainter class that does the painting, it is only a one line change. However, I refactored the code a bit to isolate this painting code from the code that determines the area to be painted. This will allow for easier customizations that you may want to do in the future.
The following code was used to creating the highlightings shown in the image:
RectanglePainter red = new RectanglePainter( Color.RED );
RectanglePainter cyan = new RectanglePainter( Color.CYAN );
textArea.getHighlighter().addHighlight(5, 9, red);
textArea.getHighlighter().addHighlight(61, 69, cyan);
textArea.getHighlighter().addHighlight(106, 110, red);
The SquigglePainter is an example of a painter that will underline the text with a squiggly line. You may want to play with the squiggle size to see what you prefer. I would recommend 2 or 3 otherwise the squiggle gets too big.
There is not much more to say about this class. Once you have a Graphics object and a drawing area, the highlighting possibilities are only limited by your imagination. Hopefully these two examples will get you started.