How to use an .html template as a GUI for Java desktop

Java 8

The Java

public static final String url = "YOUR LOCAL PATH HERE";

WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
URL urlPath = getClass().getResource(url);
webEngine.load(urlPath.toExternalForm());


The code above specifies where your .html file lives

The code above creates a WebView object (Java's native web browser) which can be run in JavaFX

The core JavaFX code is provided below

//Extend the FX Application abstract class
public class WebViewDemo extends Application {
    public static final String url = "YOUR LOCAL PATH HERE";

    //The necessary main method with launch args
    public static void main(String[] args) {
        launch(args);
    }

    //Override the start method
    //FX executes this method automatically after main method
    @Override
    public void start(final Stage stage) {
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        URL urlPath = getClass().getResource(url);
        webEngine.load(urlPath.toExternalForm());

        JSObject jso = (JSObject) webEngine.executeScript("window");
        jso.setMember("java", new JSUpcall());

        //Place the WebView object into the Scene
        Scene scene = new Scene(webView);

        //Set FX stage
        stage.setTitle("Application Example");

        //Set FX scene
        stage.setScene(scene);

        //Set fixed dimensions  
        stage.setMaxHeight(605);
        stage.setMaxWidth(850);
        stage.setMinHeight(605);
        stage.setMinWidth(850);
        stage.show();
    }
}


The code below registers a Java class with a JavaScript handle - here we use javaHandle

JSObject jso = (JSObject) webEngine.executeScript("window");
jso.setMember("javaHandle", new JSUpcall());


Below is the Java class we expose to the JavaScript

Any associated JavaScript code executed within the WebView will make an upcall into the Java layer enabling the associated Java to be executed without Struts or any other additional machinery (which aren't available desktop-wise anyway)

All public methods within the class are exposed thereby

public class JSUpcall {
    public void exampleMethod(args){
        //Logic Here;
    }
}


The JavaScript

Include this in your .html's script assets where desired

java.exampleMethod(args);


Additional Concerns

Warning: the .html accessed by Java at runtime cannot be part of the classpath - it must reside independently of the compiled Java .jar