Friday, March 23, 2012

Generate and load html content dynamically using Java code

In this example, the html content in WebView is generated in run-time by Java code dynamically.

Generate and load html content dynamically using Java code

package javafx_webview;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

* @web
public class JavaFX_Browser extends Application {

private Scene scene;
MyBrowser myBrowser;

* @param args the command line arguments
public static void main(String[] args) {

public void start(Stage primaryStage) {

myBrowser = new MyBrowser();
scene = new Scene(myBrowser, 640, 480);


class MyBrowser extends Region{

WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();

public MyBrowser(){



private String genHtml(){

StringBuilder tHtml = new StringBuilder();

tHtml.append("<DOCTYPE html>" + "\n");
tHtml.append("<html lang='en-US'>" + "\n");
tHtml.append("<head>" + "\n");
tHtml.append("<meta charset=utf-8>" + "\n");
tHtml.append("<title>Hello Java-Buddy!</title>" + "\n");
tHtml.append("</head>" + "\n");
tHtml.append("<body>" + "\n");
tHtml.append("<p>Hello <a href=''>Java-Buddy</a></p>" + "\n");
tHtml.append("<img src=''/>" + "\n");
tHtml.append("</body>" + "\n");
tHtml.append("</html>" + "\n");

return tHtml.toString();

- Load local html in JavaFX WebView
- Add toolbar in our browser


  1. That really helped me to kick start my solution. When I tried to insert jquery mobile css and js file it seems that it stops rendering the hrml. Do you have any suggestion? We have also post to Javafx forums but no luck.

  2. Instead of setting the default size of 640x480, is there a way with the WebView to get the preferred size of the content? The WebView class has a prefWidth() and prefHeight() methods but they only contain the default size of the component (800x600). I want to pack my window to fit the required dimensions of the html to limit whitespace because I'm not displaying a website, just html-formatted text (ie. [html][body]Hello, World![/body][/html]