Skip to content
Advertisement

Java JEditorPane – Trying to edit an html tag value and getting Exception

I have a JEditorPane and I’m trying to edit one fo the html element attributes, basically changing the the src x value in to a custom value

The code I have is:

JavaScript

I get the following exception in the before last line when I try to remove the existing attribute (because you can’t replace):

JavaScript

I read a few places that you can use writeLock, but that’s a protected method, which means I can’t call it from this code…

So basically my question is that if you’ve found the element you want, how do you edit it’s attributes?

Advertisement

Answer

The problem is that HtmlDocument requires you perform a writeLock before trying to change any attributes and a writeUnlock after. So to solve this I had to:

First extend the EditorKit for my JEditorPane to use a custom HtmlDocument. Then I extended the HTMLDocument to make the writeLock and writeUnlock publicly accesible:

JavaScript

Then I did:

JavaScript

Now I could in code above, all I have to do is call the lock before trying to edit the attributes, and unlock when I’m done:

JavaScript

And everything works as expected. I’m able to modify and edit the attributes in the document.

I guess what I now don’t fully understand or appreciate is why you can’t access the writeLock and writeUnlock publicly? Why have they been setup as protected? What where the programmers trying to prevent you from doing and why?

Advertisement