Making a simple overlay class

gwtjsnisvg

I'd like to make some really simple overlay classes in GWT to wrap some SVG stuff. I'd basically like to get a rectangle drawn, this is how I do it in javascript:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '100%');
svg.setAttribute('height', '100%');
document.body.appendChild(svg);

var rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
rect.setAttribute("width","300");
rect.setAttribute("height","100");
svg.appendChild(rect);

and now I'm having trouble translating that to GWT. I was hoping I could do a really thin overlay around all those calls, something like this:

public class SVGPanel extends JavaScriptObject {
    protected SVGPanel() {}

    public static native SVGPanel create(String width, String height) /*-{
        var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.setAttribute('width', width);
        svg.setAttribute('height', height);
        return svg;
    }-*/;
}

public MyProject implements EntryPoint {

    public void onModuleLoad() { 
        SVGPanel panel = SVGPanel.create("100%", "100%");
        Document.get().getBody().appendChild(panel);
    }
}

yeah but I do not have a grasp on how we can jump from the javascript representation of the SVG stuff to GWT java classes. For one, the SVGPanel class extends JavaScriptObject, but I can't simply add it to the Document body class because it's expecting an Element type. If someone could just point out the right way to do that bridge I should be able to get going after that.

Also, I'm not sure if this the optimal way to incorporate some simple SVG classes, should I be modeling them using the DOM classes instead of trying to use JSNI ?

Thanks

Best Answer

You need to give an Element to appendChild. So just make your overlay class extend Element instead of JavaScriptObject.

public class SVGPanel extends Element {

Note that Element is a subclass of JavaScriptObject.

Related Topic