Search code examples
javastringlibrarieshighlightjtextarea

Remove Hightlight matching String content


Ok, few days ago I made one post regarding to the remove of Hightlighted text in JTextArea:

Removing Highlight from specific word - Java

The thing is, that time I made one code to remove Hightlights macthing its size...but now I have a lot of words with the same size in my app and obviously the application isnt running right.

So I ask, Does anyone know a library or a way to do this removal macthing the content of each highlighted string?


Solution

  • You could write a method to get the text for a given highlighter:

    private static String highlightedText(Highlight h, Document d) {
        int start = h.getStartIndex();
        int end = h.getEndIndex();
        int length = end - start;
        return d.getText(start, length);
    }
    

    Then your removeHighlights method would look like this:

    public void removeHighlights(JTextComponent c, String toBlackOut) {
        Highlighter highlighter = c.getHighlighter();
        Highlighter.Highlight[] highlights = h.getHighlights();
        Document d = c.getDocument();
        for (Highlighter.Highlight h : highlights)
            if (highlightedText(h, d).equals(toBlackOut) && h.getPainter() instanceof TextHighLighter)
                highlighter.removeHighlight(h);
    }