Sunday, May 27, 2012

JavaFX 2: WebView

This is a tutorial about adding HTML content to JavaFX 2 applications. Here, we will load some web page, and display it in an embedded browser. The embedded browser component is based on WebKit, an open source web browser engine. It supports Cascading Style Sheets (CSS), JavaScript, Document Object Model (DOM), and HTML5.

The embedded browser enables you to perform the following tasks in your JavaFX applications:
  • Render HTML content from local and remote URLs
  • Execute JavaScript commands
  • Perform upcalls from JavaScript to JavaFX.
  • Manage web pop-up windows
  • Apply effects to the embedded browser
Below you can take a look how our example will look in the end.
WebView
JavaFX 2 WebView
As can be seen from the code, it's a short and easy tutorial to follow. We will first, add our WebView browser and then load a web page with WebEngineBelow is shown the typical way to create WebView and WebEngine objects in your application.

WebView browser = new WebView();
WebEngine engine = browser.getEngine();
String url = "http://zoranpavlovic.blogspot.com/";
engine.load(url);


Here is the  code of JavaFX 2 WebView example:


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class WebViewMain extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("WebView test");
WebView browser = new WebView();
WebEngine engine = browser.getEngine();
String url = "http://zoranpavlovic.blogspot.com/";
engine.load(url);
StackPane sp = new StackPane();
sp.getChildren().add(browser);
Scene root = new Scene(sp);
primaryStage.setScene(root);
primaryStage.show();
}
}

If you like this, and other JavaFX 2 tutorials on this blog, you can like this blog on Facebook to be informed about new JavaFX tutorials.



2 comments:

  1. hi i want to open four urls in a single page can you please help me
    please send me example code in j2se

    ReplyDelete
  2. My code is below and is failing to load the webView with the content. How can i best do it. Please help. Thanks



    package octopushr;

    import java.net.URL;
    import java.util.ResourceBundle;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.web.WebEngine;
    import javafx.scene.web.WebView;

    public class AboutController implements Initializable {

    @FXML
    private WebView webView;

    @FXML
    private WebEngine engine;
    @Override
    public void initialize(URL url, ResourceBundle rb) {
    engine = webView.getEngine();
    engine.load("http://zoranpavlovic.blogspot.com/");
    }

    }

    ReplyDelete