I'm just trying to dynamically add children to the parent through a public method. If I call canvasContainer.add(Canvas.createIfSupported()) from inside the constructor, it works as intended, but from inside the insertLayerAt() method, it silently fails, not appending to the DOM.

I've tried using different Panels as the parent element, and different Widgets as the child element, but the problem persists.

Am I approaching this wrong? I can't find anything that says I shouldn't be using the add method from outside the constructor, but then again I might be missing something simpler than that.

My code is below, I'm using GWT 2.4 and MVP4G

public class CanvasView extends Composite implements
        CanvasPresenter.ICanvasView {

    LayoutPanel canvasContainer;

    @Inject
    public CanvasView()
    {
        Document document = Document.getInstance();
        Dimension d = document.getDimension();


        canvasContainer = new LayoutPanel();
        canvasContainer.setPixelSize(d.width, d.height);
        canvasContainer.setStyleName("CanvasController");

        initWidget(canvasContainer);


    }

    public void insertLayerAt(int zpos, Layer layer)
    {

        Canvas canvas = Canvas.createIfSupported();
        if (canvas != null)
        {
            GWT.log("Canvas is supported.", null);              
            canvasContainer.add(canvas);

        }else{
            GWT.log("Canvas isn't supported.", null);
        }
    }


}
1

There are 1 answers

0
user0b101010 On

Using a deferred command helps sometimes when stuff like this happens if the reason is that there's something it's not finished with. I haven't tried this code though, so I have no idea if it works in this case.

public void insertLayerAt(int zpos, Layer layer)
{

    Canvas canvas = Canvas.createIfSupported();
    if (canvas != null)
    {
        GWT.log("Canvas is supported.", null);              
        Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {         
            public void execute() {
                    canvasContainer.add(canvas);
            }
         });
    }else{
        GWT.log("Canvas isn't supported.", null);
    }
}