Search code examples
javadomsvgbatik

Adding an element to a DOM document with batik


Good evening,

My problem is when adding an element (rectangle) to my DOM document.

The addition is done as follows:

Creating an element rect light blue / fluo

Node node = doc.createElement("rect");
Element elem = (Element)node;
elem.setAttribute("fill", obj.getColor());

Contained in a group of elements g

Node newZone = doc.createElement("g");
Element elemZone = (Element)newZone;
elemZone.setAttribute("id", zone);

Adding the element rect to the element g

elemZone.appendChild(elem);

Adding to the document

doc.getElementById(idUse).appendChild(elemZone);

Updating the document JSVGCanvas (which allows the display svg)

svg.setDocument(doc);

So also weird as it may seem, the change is taken into account, because when I save the document and displays the file, I see the change.

But nothing in the application is updated.

Also, I added an element (symbol + use) following the same process. JSVGCanvas and update the document is well considered and also visible.

Thank you in advance for your help ...

Remarks: - Repaint tested np times. - Launching the application with the document: The rectangle appears good.


Solution

  • SVG elements must be created in the SVG namespace so replace

    Node node = doc.createElement("rect");
    

    by

    Node node = doc.createElementNS("http://www.w3.org/2000/svg", "rect");
    

    Same with the <g> element. Serialising and unserialising the document will fix the namespace problem which is why you don't see it on reload.

    For Batik you must also call

    jsvgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
    

    before loading the content too, and make all changes in the update manager's thread.