Search code examples
javaswingjtextpane

JTextPane highlight text


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.


Solution

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