I create a simple Javascript file containing a simple button.
function testfuncion() {
document.write('<input type="button" name="hello" value="hello">');
}
Then I created a HTML panel in gwt.
HTML panelHtmlTry = new HTML();
How can put the Javascript button into the HTML panel?
In this experiment I can't create the button in gwt but only put a Javascript object into the gwt panel.
PS: i can use html panel or horizzontal panel. My objective is put a javascript button on each GWT panel and show it
Yeah, there is a simpler way to do what you want. But if you want to do what you want. You can call the custom JavaScript method through JSNI.
This JSNI method calls your custom JS script, which is included in the host page.
private native void testfunction() /*-{
$wnd.testfuncion();
}-*/;
$wnd is a reference to the browsers window
object see GWT Docs on JSNI
Then you can call this JSNI method anywhere in your GWT code:
testfunction();
And every time, the JavaScript function from the file gets called through JSNI.
You can temporarily redifine document.write, so that it sets the button in the HTML
widget you wish.
private native void testfunction(HTML html) /*-{
var originalWriteFunc = $wnd.document.write;
$wnd.document.write = function(str) {
html.@com.google.gwt.user.client.ui.HTML::setHTML(Ljava/lang/String;)(str);
};
$wnd.testfuncion();
$wnd.document.write = originalWriteFunc;
}-*/;
So you need to call testfunction, with the HTML widget, where the button should be positioned.
Given that no modifications are allowed to the JS file, and assuming the input
is the only input
in the document, you could extend HTML
to wrap the input
element:
public class MyInputHtml extends HTML {
public MyInputHtml() {
// initialize DOM with external script content
testfunction();
// set the DOM element as the widget's element
Element body = RootPanel.get().getElement();
Element el = body.getElementsByTagName("input").getItem(0);
setElement(el);
}
private native void testfunction() /*-{
$wnd.testfuncion();
}-*/;
}
It'll be best, of course, if you assign the input
with an id
. That way you can look it up simply by calling RootPanel.get(id)
, thus avoiding the need for an index based search. This will robust your code, as changes in the DOM won't affect this lookup.
Let your testFunction return a string. This you can insert into your panelHtmlTry.