Monday, 13 July 2015

HTML5 Browser Apps with Java - TeaVM part 2

I took an initial look at TeaVM - a technology for developing HTML5/Javascript web applications using Java as the development language. The first signs were promising - it was easy to get started, and the learning curve looked to be a fairly shallow one for any developers who are already familiar with Java.

The next task was to determine how easy it would be to develop real applications. That means knowing how to implement commonly needed application features: creating a user interface, responding to user actions, loading data, and manipulating on-screen elements. To that end, here are some of code examples to illustrate how to do common tasks...

1. Handling user interface events
<button id="myButton">Click Me</button>
HTMLButtonElement myButton = (HTMLButtonElement) 
    myButton.addEventListener("click", new EventListener<Event>() {
    public void handleEvent(Event evt) {
        //button was clicked
2. Loading an image
HTMLImageElement imgElt = (HTMLImageElement)
imgElt.addEventListener("load", new EventListener<Event>() {
    public void handleEvent(Event evt) {
        //loaded image successfully
imgElt.addEventListener("error", new EventListener<Event>() {
    public void handleEvent(Event evt) {
        //failed to load image
3. Displaying an image
HTMLCanvasElement canvasElement = (HTMLCanvasElement)
CanvasRenderingContext2D context = (CanvasRenderingContext2D)canvasElement.getContext("2d");
context.drawImage(imgElt, posx, posy, width, height);

For a web application, the user interface is of course defined in HTML, so in the Java code we simply need to get handles of the existing elements (Example 1), or create them on the fly (Example 2). The classes HTMLButtonElement, EventListener, HTMLCanvasElement, CanvasRenderingContext2D and HTMLImageElement are all provided by TeaVM. If you are familiar with Javascript, you'll recognise the similarity. But of course being Java, you get the benefit of strongly-typed classes, which aid with clarity and help reduce bugs.

Another elegant feature of TeaVM is the ability to extend it if you need to use Javascript features that may be missing or not yet implemented. For example, I wanted to make use of Javascript's toFixed() method to format decimal numbers. TeaVM does not provide direct access to this function via its own APIs, but does provide a method to access arbitrary Javascript using a mechanism called JSO. It works using Java annotations to declare Javascript references, like this:
import org.teavm.jso.JSBody;

public class JSFormatter {
    @JSBody(params = { "f", "n" }, script = "return f.toFixed(n);")
    public static native String toFixed(float f, int n);
I'll write up my conclusions on TeaVM in the next article.

No comments:

Post a Comment