Highlighting Words in a JTextComponent

This example demonstrates how to highlight a range of characters in a text component using highlights. The example uses a text component's highlighter to create and manage the highlights. Since one of the highlights in the highlighter is the selection, we must be careful when removing highlights not to remove the selection.

The way in which we identify our highlights is to create the highlight using a private painter. So when removing highlights from the highlighter, we remove only the ones whose painter is an instance of the private painter.

If many different highlight styles are required, it is necessary to use styles with a JTextPane. See Setting the Font and Color of Text in a JTextPane Using Styles for more details.

JTextArea textComp = new JTextArea();

// Highlight the occurrences of the word "public"
highlight(textComp, "public");

// Creates highlights around all occurrences of pattern in textComp
public void highlight(JTextComponent textComp, String pattern) {
    // First remove all old highlights
    removeHighlights(textComp);

    try {
        Highlighter hilite = textComp.getHighlighter();
        Document doc = textComp.getDocument();
        String text = doc.getText(0, doc.getLength());
        int pos = 0;

        // Search for pattern
        while ((pos = text.indexOf(pattern, pos)) >= 0) {
            // Create highlighter using private painter and apply around pattern
            hilite.addHighlight(pos, pos+pattern.length(), myHighlightPainter);
            pos += pattern.length();
        }
    } catch (BadLocationException e) {
    }
}

// Removes only our private highlights
public void removeHighlights(JTextComponent textComp) {
    Highlighter hilite = textComp.getHighlighter();
    Highlighter.Highlight[] hilites = hilite.getHighlights();

    for (int i=0; i<hilites.length; i++) {
        if (hilites[i].getPainter() instanceof MyHighlightPainter) {
            hilite.removeHighlight(hilites[i]);
        }
    }
}

// An instance of the private subclass of the default highlight painter
Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);

// A private subclass of the default highlight painter
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
    public MyHighlightPainter(Color color) {
        super(color);
    }
}

Comments

3 Feb 2010 - 2:44pm by Anonymous (not verified)

Thank you - exactly what I was looking for

17 Jan 2011 - 8:44am by Yossale (not verified)

Thanks! I needed that!

20 Jun 2011 - 4:04pm by lucian (not verified)

thank you :) great article

28 Jun 2011 - 11:34am by bbuchanan (not verified)

You rock dude. Thanks!

23 Oct 2011 - 12:33am by Anonymous (not verified)

lo maximo tio!! la hiciste

17 Jan 2012 - 11:39pm by Anonymous (not verified)

How can I change text color during highlighting if text and higligting background colors are same? Thanks.

27 Mar 2012 - 12:50pm by 2xM (not verified)

Freakin awesome...been googling this thing for some time now and this is by far the cleanest peace of code

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.