Skip to content

Instantly share code, notes, and snippets.

@jtulach
Last active August 13, 2016 09:30
Show Gist options
  • Save jtulach/7102188 to your computer and use it in GitHub Desktop.
Save jtulach/7102188 to your computer and use it in GitHub Desktop.
Counting button clicks in Java with low level JavaScript interaction
package dew.demo.lowlevel;
import net.java.html.js.JavaScriptBody;
final class Java2JsAndBack implements Runnable {
private int cnt = 0;
@Override public void run() {
String msg = "I was pressed";
if (++cnt > 1) {
msg += " " + cnt + " times";
}
changeText("button", msg);
}
//
// Java/JS bridge utility methods. Visit
// http://bits.netbeans.org/html+java/1.3/net/java/html/js/package-summary.html
// to learn how to use the @JavaScriptBody annotation
//
@JavaScriptBody(args = { "id", "text" }, body =
"var e = window.document.getElementById(id);\n" +
"e.innerHTML = text;"
)
public static native void changeText(String id, String text);
@JavaScriptBody(args = { "id", "r" },
javacall = true, body =
"var e = window.document.getElementById(id);\n" +
"e.onclick = function() {" +
" [email protected]::run()();" +
"};"
)
public static native void onclick(String id, Runnable r);
//
// initialization
//
static {
Java2JsAndBack handler = new Java2JsAndBack();
onclick("button", handler);
}
}
<button id="button">Press me!</button>
@jtulach
Copy link
Author

jtulach commented Oct 29, 2013

See the live snippet by visiting its DEW at http://dew.apidesign.org/dew/#7102188

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment