0

I need to be able to highlight the words within two chars. For example, :

//Highlight whatever is in between the two quotation marks
String keyChars = " \" \" ";

I have been grueling over this for weeks now. I've looked it up, read source codes, wrote code, and still I have yet to find out how I would be able to do this.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2228462
  • 589
  • 1
  • 5
  • 14
  • *"wrote code,"* What have you tried, specifically? How did it fail? – Andrew Thompson Apr 09 '13 at 04:23
  • Check out [this](http://stackoverflow.com/questions/13448558/highlight-a-word-in-jeditorpane/13449000#13449000) example, it uses a `JEditorPane` but the concept should be the same – MadProgrammer Apr 09 '13 at 04:35
  • Here is an hint try searching for DefaultHighlighter.DefaultHighlightPainter class. And Check what is a Regex. – Jayamohan Apr 09 '13 at 04:39
  • 2
    I'm guessing this is related to his other question (http://stackoverflow.com/questions/15867900/java-auto-indentation-in-jtextpane) where he is trying to do syntax highlighting by playing with AttributeSets. I'm also guessing he is looking for an algorithm to find quoted literals that contain escaped quotes. – camickr Apr 09 '13 at 05:08
  • Sorry for the late response. In answer to camickr, this isn't really related to that question. Before I asked the question in the link, I didn't have the highlighting quotation marks. Saying that, thanks for all the responses so far! – user2228462 Apr 09 '13 at 12:37

1 Answers1

1

The following code snippet works.

ed=new JEditorPane();
ed.setText("This \"text\" contains \"quotes\". The \"contents\" of which are highlighted");
Pattern pl;
pl=Pattern.compile("\"");
Matcher matcher = pl.matcher(ed.getText());
int end=0,beg=0;
while(matcher.find())
{
    beg=matcher.start();
    matcher.find(); //finding the next quote
    end=matcher.start();
    DefaultHighlightPainter d =  new DefaultHighlightPainter(Color.YELLOW);
    try {
        ed.getHighlighter().addHighlight(beg+1, end,d);
    } catch (BadLocationException ex) {
        ex.printStackTrace();
    }
}
Rishabh
  • 199
  • 3
  • 14
  • Thanks for the response, although unfortunately that's not what I was looking for - my fault, because I wasn't clear enough with my question. What I should have said was "live highlighting" between two characters. My bad. – user2228462 Apr 09 '13 at 12:46