Question

I'm trying to search and highlight words in my JTextPane. It works wonderfully with words that don't have a lot of results so far but when I try to search for a word that has a lot instances, sometimes, the highlighter highlights the result way off, like it misses it by a number of characters. Anyway, here is the code that I used to this end.

    int index = 0;
    String text = null;
    try {
    int length=textPane.getDocument().getLength();
    text = textPane.getDocument().getText(0,length);
    } catch (BadLocationException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }  
    try {
     while ((index = text.indexOf(myWord, index)) >= 0) {
    DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
    textPane.getHighlighter().addHighlight(index, index+myWord.length(), highlightPainter);
    index += myWord.length();

    }

    } catch (BadLocationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }

Here's a screenshot that describes the problem http://i.imgur.com/po6U0rh.png Red Circle= Wrong Result, Green Circle= Right Result.

Thank you in advance for your help.

Was it helpful?

Solution

I don't know if that usage of Highlighter is supported. From what I can tell, Highlighter is only meant be used by javax.swing.text.View and its related classes.

I would do it this way:

StyledDocument document = textPane.getStyledDocument();
Style highlight = document.addStyle("highlight", null);
StyleConstants.setBackground(highlight, Color.YELLOW);

String text = document.getText(0, document.getLength());
while ((index = text.indexOf(myWord, index)) >= 0) {
    document.setCharacterAttributes(index, myWord.length(), highlight, false);
    index += myWord.length();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top