gpt4 book ai didi

java - 获取 'Attempt to mutate notification' 异常

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:08:44 25 4
gpt4 key购买 nike

我的目标是将用户写入 JTextPane 的关键字着色为蓝色。这是我的代码的样子:

private class DocumentHandler implements DocumentListener {

@Override
public void changedUpdate(DocumentEvent ev) {
}

@Override
public void insertUpdate(DocumentEvent ev) {
highlight();
}

@Override
public void removeUpdate(DocumentEvent ev) {
highlight();
}

private void highlight() {
String code = codePane.getText();
SimpleAttributeSet defSet = new SimpleAttributeSet();
StyleConstants.setForeground(defSet, Color.BLACK);
doc.setCharacterAttributes(0, code.length(), defSet, true);
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setForeground(set, Color.BLUE);
for (String keyword : keywords) {
Pattern pattern = Pattern.compile(keyword + "(\\[\\])*");
Matcher matcher = pattern.matcher(code);
while (matcher.find()) {

//Just for test
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end());
System.out.println(" Found: " + matcher.group());

doc.setCharacterAttributes(matcher.start(), keyword.length(), set, true);
}
}
}
}

在 Pane 中输入任何内容后,我得到:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification
at javax.swing.text.AbstractDocument.writeLock(AbstractDocument.java:1338)
at javax.swing.text.DefaultStyledDocument.setCharacterAttributes(DefaultStyledDocument.java:500)
at jnotepad.MainPanel$DocumentHandler.highlight(MainPanel.java:121)
at jnotepad.MainPanel$DocumentHandler.insertUpdate(MainPanel.java:108)
at javax.swing.text.AbstractDocument.fireInsertUpdate(AbstractDocument.java:202)
at javax.swing.text.AbstractDocument.handleInsertString(AbstractDocument.java:749)

如何解决我的问题?也许我应该使用 DocumentListener 以外的东西?

最佳答案

您需要从事件调度程序线程调用对文档的更改。

试试这个:

private void highlight() {

Runnable doHighlight = new Runnable() {
@Override
public void run() {
// your highlight code
}
};
SwingUtilities.invokeLater(doHighlight);
}

关于java - 获取 'Attempt to mutate notification' 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15206586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com