Posted by Rob Camick on October 29, 2008
You have a text component that dislays multiple lines of text. Now you want to highlight the current line at the position of the caret. One possible way to do this might be to use a highlighter (as discussed in the last blog) and then adjust the highlight offsets whenever the caret changes location. The problem is that the default highlight painter will only highlight where text is painted. That is, the empty space to the right of the text is never highlighted. We want to highlight the entire line whether text goes to the end or not.
It won’t be a big change as we can still use the functionality of the highlighter to schedule the painting of highlights. So, we will add a dummy highlight to the text component that will use our custom painter. Now whenever the highlighter invokes our painter, we will simply ignore the Shape area passed to the painter and calculate our drawing area to be the entire width of the text component. We will still respect the height of the Shape area.
The LinePainter class can be used on any text component. You need to specify the text component to be highlighted so the various listeners used to track caret movement can be installed. In addition to painting the currently highlighted line, the LinePainter will be responsible for removing the highlight from the previous line. You also have the option to specify the line highlight color or use the default color. The default color will be calculated by using the existing text component selection color and then make it lighter. The color is made lighter by multiplying the RGB values of the selection color by a factor of 1.2.
The line painter in the image below was added by using:
LinePainter painter = new LinePainter(textPane);