user2228462
user2228462

Reputation: 619

Java - Highlighting Text Between two Chars - JTextPane

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.

Upvotes: 0

Views: 580

Answers (1)

Rishabh
Rishabh

Reputation: 199

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();
    }
}

Upvotes: 1

Related Questions