Java JEditorPane - 尝试编辑 html 标签值并出现异常

标签 java html swing jeditorpane

我有一个 JEditorPane,我正在尝试编辑 html 元素属性,基本上将 src x 值更改为自定义值

我的代码是:

// Get <img src="..."> tag
RunElement imageTagElement = getImageTagElement(htmlDocument);

// Print src attribute value
System.out.println("src : " + runElement.getAttribute(HTML.Attribute.SRC));

// Replace existing src value 
runElement.removeAttribute(HTML.Attribute.SRC);
runElement.addAttribute(HTML.Attribute.SRC, "customValue");

当我尝试删除现有属性时,在最后一行之前出现以下异常(因为无法替换):

javax.swing.text.StateInvariantError: Illegal cast to MutableAttributeSet

我读到了一些可以使用 writeLock 的地方,但这是一个 protected 方法,这意味着我无法从此代码中调用它...

所以基本上我的问题是,如果您找到了所需的元素,如何编辑它的属性?

最佳答案

问题是 HtmlDocument 要求您在尝试更改任何属性之前执行 writeLock,并在之后执行 writeUnlock。所以为了解决这个问题我必须:

首先扩展 JEditorPane 的 EditorKit 以使用自定义 HtmlDocument。然后我扩展了 HTMLDocument 以使 writeLock 和 writeUnlock 可公开访问:

public class ExtendedHTMLDocument extends HTMLDocument
{
    public void hackWriteLock()
    {
        writeLock();
    }

    public void hackWriteUnlock()
    {
        writeUnlock();
    }
}

然后我做了:

public class ExtendedEditorKit extends HTMLEditorKit
{
    @Override
    public Document createDefaultDocument()
    {
        // For the left out code copy what's in the super method
        ..
        HTMLDocument doc = new ExtendedHTMLDocument(ss);
        ..
    }
}

现在我可以在上面的代码中,我所要做的就是在尝试编辑属性之前调用锁定,并在完成后解锁:

// lock
htmlDocument.hackWriteLock()

// Get <img src="..."> tag
RunElement imageTagElement = getImageTagElement(htmlDocument);

// Print src attribute value
System.out.println("src : " + runElement.getAttribute(HTML.Attribute.SRC));

// Replace existing src value 
runElement.removeAttribute(HTML.Attribute.SRC);
runElement.addAttribute(HTML.Attribute.SRC, "customValue");

// unlock
htmlDocument.hackWriteUnlock()

一切都按预期进行。我能够修改和编辑文档中的属性。

我想我现在不完全理解或欣赏的是为什么你不能公开访问 writeLock 和 writeUnlock ?为什么它们被设置为 protected ?程序员试图阻止你做什么以及为什么?

关于Java JEditorPane - 尝试编辑 html 标签值并出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17638394/

相关文章:

java - 我想使用spring boot和hibernate创建表,虽然没有报错,但是无法创建表,为什么?

css - 在固定的 div 中居中两个宽度可变的 css div

java - 在 Java Swing 中循环遍历容器内的嵌套容器

java - 在 Geotools 中构建 Shapefile 时遇到问题

java - 我应该使用什么 Java DateTime 类?

java - 如何告诉 Eclipse 工作区?

html - Css Rotate 45 导致渐变边框中断

javascript - 清除 SELECT 中的所有选择

java - 如何根据单元格中的值对 JTable 的各个单元格着色?

java - Eclipse:Java,找不到主要方法