不为JTextPane中的所有匹配单词着色

不为JTextPane中的所有匹配单词着色

本文介绍了Java正则表达式-不为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);
    }
}

但是,在包含很多注释的JTextPane上,有些单词没有上色

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

推荐答案

您的代码检索注释文本(getkomen=komen.group()),然后搜索该文本的 first 实例(...indexOf(getkomen)) .如果您有多个相同的注释,则仅第一个注释将被上色.

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.

Matcher 将使用 start() end() .您应该只使用那些.

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

这篇关于Java正则表达式-不为JTextPane中的所有匹配单词着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 08:07