JTextPane highlight text

xdevel2000 picture xdevel2000 · Apr 15, 2011 · Viewed 18.7k times · Source

Can I highlight some text into a JTextPane starting from a value and ending from another value like the following but with the yellow color?

"" JTextPane highlight text ""

Thanks.

Answer

kleopatra picture kleopatra · Apr 15, 2011

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);