Search code examples
javaswinghighlightjtextareaswing-highlighter

Removing Highlight from specific word - Java


I want to build one sample to remove highlight from words that matches the filter of my app. Therefore I was basing myself on the sample below:

    public void removeHighlights(JTextComponent jTextArea) {

        Highlighter hilite = jTextArea.getHighlighter();
        Highlighter.Highlight[] hilites = hilite.getHighlights();

        for (int i = 0; i < hilites.length; i++) {
            if (hilites[i].getPainter() instanceof TextHighLighter) {
                hilite.removeHighlight(hilites[i]);
            }
        }
    } 

This sample works to remove all highlights of the Text Area. For example, if I have three selected words and I uncheck the box of one, all of the filters will be removed and I only want to remove the highlight of the unchecked word.. Is there a simple way to check which word matches the filter? or do I need to do it manually? cos until now I found nothing sucessful on my research

Thanks in advance

FINAL EDIT :

Logic working for me based on @camickr answer:

public void removeHighlights(JTextComponent jTextArea, String turnLightOff) {


           Highlighter hilite = jTextArea.getHighlighter();

           Highlighter.Highlight[] hilites = hilite.getHighlights();

           for (int i = 0; i < hilites.length; i++) {

              int wordLenght = hilites[i].getEndOffset() - hilites[i].getStartOffset();

              if(wordLenght == turnLightOff.length()){

                  if (hilites[i].getPainter() instanceof TextHighLighter) {

                      hilite.removeHighlight(hilites[i]);
              }

              }
           }                
}

Solution

  • Is there a simple way to check which word matches the filter?

    No.

    or do I need to do it manually?

    Yes. Each highlight contains the start/end offset of the highlight. So you use those values to get the text from the Document. If the text matches, then remove the highlight.