Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom widget to an element

Tags:

gwt

GWT RootPanel.get("id") doesnt return me the div tags which are embedded in HTML elements.

ex. <body> <table> <tr> <td> <div id="x" /><td>...</table> ...

How do I get access to this div tag and "Add a widget".

One of the things I tried was to get the element from the widget or widget.getElement() and add this to the append this element to an element gotten from DOM.getElementById().

The widget does get added, however, all mouse clicks are lost and widget no longer responds. The widget is a composite of menu item, so the mouse clicks cause the menu item to drop but it just selects the text.

like image 407
justanothercoder Avatar asked May 31 '11 05:05

justanothercoder


2 Answers

If by "HTML element" in your first sentence you actually mean "HTML widget", then you should use an HTMLPanel widget instead, and then simply use its add(Widget,String) or add(Widget,Element) method to add your widget within an existing sub-element.

If you're actually talking about the "A widget that has an existing parent widget may not be added to the detach list" assertion error, then starting with GWT 2.3, you can now wrap an existing DOM element within an HTMLPanel, and then use the same add methods as above:

HTMLPanel container = HTMLPanel.wrap(Document.get().getElementById("container"));
like image 65
Thomas Broyer Avatar answered Oct 07 '22 22:10

Thomas Broyer


Your approach with DOM.getElementById() is the correct one. GWT Widgets create an object tree parallel to DOM, so you have to additionally "attach" this object tree to DOM to receive events. This is done via onAttach() method.

Unfortunately this method is protected so you can not call it directly. A workaround is to create a simple Widget wrapper class and make it public:

public void onAttach() {
    super.onAttach();
}

Note that you must make sure that Widget is detached when not shown any more as failing to do so can leak memory. The easiest way to do this is to call RootPanel.detachOnWindowClose(widget).

Update:

As Thomas Broyer said (and his words are to be considered as "the source") - use HTMLPanel.wrap(yourDivElement) as this will correctly do what you need it to do - attach Widget to DOM tree.

My proposed approach is hackish and I'd recommend it only if you are actually writing a new Widget (as I needed to do in one of my projects and copied my code here).

like image 20
Peter Knego Avatar answered Oct 07 '22 23:10

Peter Knego