1

I would like to highlight words matching a regular expression in a JTextPane.

I've seen various examples but they all where very complicated with complete syntax highlighting. I just want to highlight (or set in bold) a word/sentence, is there a simple way to do that?

Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261

1 Answers1

1

If the overall underlying text of what is in the JTextPane is just a regular string and not HTML:

  1. Get the underlying document from the JTextPane.

    StyledDocument sdoc = textpane.getStyledDocument()

EDITED: changed to directly calling textPane.getStyledDocument, instead of casting the result of getDocument()

  1. Get the text of the document.

    String text = sdoc.getText(0, sdoc.getLength())

  2. Use the Pattern and Matcher classes to find the locations that match the regular expression. I assume you already know how to do that.

  3. For every location where a match is found, highlight the start to end of the matching substring with sdoc.setCharacterAttributes or use a highlighter (see JTextPane highlight text)

Community
  • 1
  • 1
Gigatron
  • 1,995
  • 6
  • 20
  • 27