Highlighters

Highlighters determine how text is marked to make it stand out. The order in which we discuss the highlighter interfaces may seem counterintuitive. The basic Highlighter interface is so straightforward that you’ll rarely need to work with it directly, so we will describe it later. At this point, we discuss the interface you’re most likely to use first: the Highlighter.HighlightPainter interface.

The Highlighter.HighlightPainter Interface

This is an inner interface of the Highlighter interface. If you want to change the way that highlights are drawn in your text component, this is the interface you’d implement.

Implementations of Highlighter.HighlightPainter are returned by Caret implementations and passed to Highlighter implementations (described later in this section; there are a lot of interfaces working together), which use them to decorate the area “behind” a selection. The only concrete implementation that’s provided in Swing is DefaultHighlighter.DefaultHighlightPainter, which paints highlights as a solid background rectangle of a specified color.

This interface consists of a single paint( ) method. Unlike the paint( ) method of Caret, this method is called before the text itself is rendered, so there’s no need to worry about obscuring text or XOR mode.

Method

public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c)

Render a highlighter behind the text of the specified component. The p0 and p1 parameters specify offsets into the document model ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.