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 http://java-buddy.blogspot.com/
*/
public class JavaFX_Browser extends Application {

private Scene scene;
MyBrowser myBrowser;

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

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("java-buddy.blogspot.com");

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

primaryStage.setScene(scene);
primaryStage.show();
}

class MyBrowser extends Region{

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

public MyBrowser(){

webEngine.loadContent(genHtml());

getChildren().add(webView);
}
}

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='http://java-buddy.blogspot.com/'>Java-Buddy</a></p>" + "\n");
tHtml.append("<img src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi46oUqWnNWLjbG8MZE3s1ljR5yGMN-vrGIJ077nAnO853BL4ufNSDj430W9acswVSbwX_b4EGi4K11aIm7OCSAhDoSr5uMQ4wYIQbppWUfxxAEDgQkJ9ni9f8Ig4Q-RP3JcaNHgjDG8s83/s150/duke_44x80.png'/>" + "\n");
tHtml.append("</body>" + "\n");
tHtml.append("</html>" + "\n");

return tHtml.toString();
}
}



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

No comments:

Post a Comment