JTextPane highlight text

As often there are several possibilities, depending on what you really mean by “highlight”:-)

Highlight by changing any style attributes of arbitrary text parts on the document level, something like

    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setForeground(sas, Color.YELLOW);
    doc.setCharacterAttributes(start, length, sas, false);

Highlight via a Highlighter on the textPane level:

    DefaultHighlighter.DefaultHighlightPainter highlightPainter = 
        new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
    textPane.getHighlighter().addHighlight(startPos, endPos, 
            highlightPainter);

Leave a Comment