Java Regex - Not coloring all matching word in JTextPane

陌路散爱 提交于 2019-12-12 00:11:52

问题


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


回答1:


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



回答2:


You can change from source.select(start, start+getkomen.length) to source.select(komen.start(),komen.end())

public WarnaText(JTextPane source) throws BadLocationException
{
    source.setForeground(Color.BLACK);
    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);
    }
}


来源:https://stackoverflow.com/questions/37649149/java-regex-not-coloring-all-matching-word-in-jtextpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!