nlight
nlight

Reputation: 43

GWT.create and wrap existing html element

Is it possible to create a TextBox using GWT.create, not the constructor, and wrap an existing HTML element? I tried:

TextBox text=GWT.create(TextBox.class)
text.setElement(DOM.createInput()) (2)

The above fails on line (2) with "cannot set element twice ..."

I need this in order to use GwtMockito and test a component that needs to create a TextBox.

Thank you!

Upvotes: 2

Views: 293

Answers (2)

Andreas Basler
Andreas Basler

Reputation: 131

UIObject have a package protected replaceElement Method which will do what you like to do.

Building a wrapper in the right package like this:

package com.google.gwt.user.client.ui;

import com.google.gwt.dom.client.Element;

public class ElementReplace
{
    public static void replaceElement(UIObject obj, Element elem)
    {
        obj.replaceElement(elem);
    }
}

and it is possible to access the method.

Upvotes: 3

Igor Klimer
Igor Klimer

Reputation: 15321

It seems you'd have to resort to using some sort of factory:

public interface TextBoxFactory {
    TextBox wrap(Element element);
}

This will get injected into your view and you'll use the factory to wrap the existing element in a TextBox. The default implementation will, of course, just use TextBox#wrap(Element), as suggested by Baz. For the purposes of your tests, you'll use an implementation that returns a Mockito mock.

Not the prettiest solution, but given the circumstances, I can't think of a "cleaner" one.

Upvotes: 2

Related Questions