0

I working on my own editor, for which I want to add a background colour to text a user might search for. Finding the text and setting a background colour is not a problem, the problem is how can I remove the background colour when the focus (highlight) is moved?

This sets the highlight:

int findPos = /* start position of user search text */
int findLength = /* length of user search text */

SimpleAttributeSet highlight = new SimpleAttributeSet();
StyleConstants.setBackground(highlight, Color.CYAN);
StyledDocument doc = jtextpane.getStyleDocument();
doc.setCharacterAttributes(findPos, findLength, highlight, false);

But how can I remove the highlight again, without affecting the foreground colours? Because the editor supports syntax highlighting, the foreground colour could be anything.

The only thing I can think of is to simply reset the entire StyledDocument and then run my highlight method over the entire thing again ... but that seems to be a terribly inefficient idea.

Eric
  • 1,321
  • 2
  • 15
  • 30
  • 1
    Instead of playing with attributes, maybe use the `Highlighter` of the text pane. This will allow you to add/remove highlights independently. – camickr Oct 29 '20 at 22:13
  • Hi @camickr thank you, from my quick test just now, it seems to work a charm :) – Eric Oct 30 '20 at 20:27

0 Answers0