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.