Search code examples
javaregexjtextpane

Java Regex - Not coloring all matching word in JTextPane


I want coloring all word that matching with commment

public WarnaText(JTextPane source) throws BadLocationException
{
    source.setForeground(Color.BLACK);
    Matcher komen=Pattern.compile("//.+").matcher(source.getText());
    while(komen.find())
    {
        String getkomen=komen.group();
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);
        aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Concolas");

        int start = source.getText().indexOf(getkomen);
        source.select(start,start + getkomen.length());

        source.setCharacterAttributes(aset, false);
    }
}

but, it some words are not colored at JTextPane which contains many comments


Solution

  • Your code retrieve the comment text (getkomen=komen.group()), then searches for the first instance of that text (...indexOf(getkomen)). If you have multiple identical comments, only the first one will be colored.

    The Matcher will give you the position of the found text using start() and end(). You should just use those.

    Matcher komen=Pattern.compile("//.+").matcher(source.getText());
    while(komen.find())
    {
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);
        aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Concolas");
    
        source.select(komen.start(), komen.end());
    
        source.setCharacterAttributes(aset, false);
    }