在JTextPane中突出显示关键字的问题

时间:2014-02-14 22:41:25

标签: java swing highlighting jtextpane

我遇到了一些问题,我编写了一些代码来浏览JTextPane中的文本并突出显示关键字(“hello”)

它工作正常,除非我从其中一个突出显示的单词中删除一个字符,然后它不再更新样式...这是我的代码:

public class ScriptEditor extends JFrame
{
    private static final long serialVersionUID = 1L;

    private static int height = 340;
    private static int width = 675;

    private boolean saved = false;

    public Pattern matcher = Pattern.compile("hello");

    private JTextPane editor = new JTextPane();

    public ScriptEditor()
    {
        super("Script Editor");
        setJMenuBar(new ScriptMenu());
        setSize(width, height);

        editor.getDocument().addDocumentListener(new DocumentListener() 
        {
            public void changedUpdate(DocumentEvent event) {}

            public void insertUpdate(DocumentEvent event)
            {
                checkForHighlights();
            }

            public void removeUpdate(DocumentEvent event)
            {
                checkForHighlights();
            }
        });

        add(new JScrollPane(editor));
    }

    private void checkForHighlights()
    {
        Runnable checker = new Runnable() 
        {
            public void run()
            {
                Matcher stringMatcher;
                try
                {
                    stringMatcher = matcher.matcher(editor.getDocument().getText(0, editor.getDocument().getLength()));

                    StyleContext style = StyleContext.getDefaultStyleContext();
                    AttributeSet black = style.addAttribute(style.getEmptySet(), StyleConstants.Foreground, Color.BLACK);
                    AttributeSet red = style.addAttribute(style.getEmptySet(), StyleConstants.Foreground, Color.RED);

                    editor.getStyledDocument().setCharacterAttributes(editor.getDocument().getLength(),     editor.getDocument().getLength(), style.getEmptySet(), true);

                    while (stringMatcher.find())
                    {
                        editor.getStyledDocument().setCharacterAttributes(stringMatcher.start(), stringMatcher.end() - stringMatcher.start(), red, false);
                    }
                }
                catch (BadLocationException e)
                {
                    e.printStackTrace();
                }
            }
        };
        SwingUtilities.invokeLater(checker);
    }

这是测试中的事件序列:

键入:“你好”(结果为红色突出显示) 类型:“世界”(结果是红色高亮圆形你好,黑色为“世界” 键入:“hello”(结果是读取高亮,如预期的那样) 键入:空格然后删除,或只删除(无更改) 类型:测试(结果是测试突出显示为红色!!!)

图片 enter image description here

谁能告诉我这里做错了什么?我该如何解决这个问题??

由于

0 个答案:

没有答案