3

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 https://i.stack.imgur.com/ywaYG.png Red Circle= Wrong Result, Green Circle= Right Result.

Thank you in advance for your help.

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
user2191986
  • 33
  • 1
  • 4
  • 1) Use a consistent and logical indent for code blocks. The indentation of the code is intended to help people understand the program flow. 2) For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Mar 27 '13 at 01:15
  • Well, that's actually a problem, I couldn't reproduce it with a simple 2-3 lines text example. The problem only appears with large texts. Anyway, I've included a copy paste source code here: http://pastebin.com/34cmPbTF – user2191986 Mar 27 '13 at 02:22

1 Answers1

2

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();
}
VGR
  • 40,506
  • 4
  • 48
  • 63
  • Okay, so it is, as [this tutorial](http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html) shows. I never knew Highlighter could be used that way. – VGR Mar 27 '13 at 02:34
  • I think you mean: document.setCharacterAttributes(index, myWord.length(), highlight, false); But that's it. It seems to have worked. Thank you very much, sir. – user2191986 Mar 27 '13 at 02:39
  • Yes I did mean that. Updated. – VGR Mar 27 '13 at 02:42