Friday, December 30, 2011

Rendering HTML Within JavaFX

JavaFX 2.0 allows for inclusion of HTML code within a JavaFX application using JavaFX 2.0's WebView and WebEngine classes from the javafx.scene.web package. This post looks at a very simple example of how this can be done. Much more sophisticated applications could enjoy more interaction between the included HTML content and the JavaFX application itself.

My simple example makes use of a JavaFX 2.0 Accordion control to present multiple Java-related sites that I frequently browse headlines ob for articles and posts to read. Each titled pane in the accordion features a different one of these web sites. The next code listing contains the entire Java class for this application and comes in at fewer than 100 lines of code including comments and white space.

WebViewExample.java
package dustin.examples;

import com.google.common.collect.ImmutableMap;
import java.util.Map;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.TitledPane;
import javafx.scene.paint.Color;
import javafx.scene.web.WebView;
import javafx.scene.web.WebViewBuilder;
import javafx.stage.Stage;

/**
 * Simple example of using JavaFX 2.0's WebView class.
 * 
 * @author Dustin
 */
public class WebViewExample extends Application
{
   /**
    * Provide an instance of a JavaFX 2.0 Accordion control with each titled
    * pane in the Accordion featuring a title based on a 'key' value in the
    * provided a map and including WebView content of the page referenced by the
    * URL in the 'value' portion of the map.
    * 
    * @param titleToUrl Mapping of page titles to their URLs to be used as
    *    titled pane titles and source of content respectively.
    * @return Accordion control with web page-based titled panes.
    */
   private Accordion prepareAccordion(final Map<String, String> titleToUrl)
   {
      final Accordion accordion = new Accordion();
      for (final Map.Entry<String,String> webMap : titleToUrl.entrySet())
      {
         final TitledPane pane =
            new TitledPane(webMap.getKey(), buildWebView(webMap.getValue()));
         accordion.getPanes().add(pane);
      }
      return accordion;
   }

   /**
    * Build a simple WebView based on the provided URL.
    * 
    * @param url URL from which content will be rendered in the provided WebView.
    * @return WebView whose content is based on web page at provided URL.
    */
   private WebView buildWebView(final String url)
   {
      final WebView webView =
         WebViewBuilder.create().prefHeight(450).prefWidth(1000).build();
      webView.getEngine().load(url);
      return webView;
   }

   /**
    * JavaFX 2.0's Application.start(Stage) method.
    * 
    * @param stage Primary stage.
    * @throws Exception Exception thrown during execution of JavaFX application
    *    stage.
    */
   @Override
   public void start(final Stage stage) throws Exception
   {
      stage.setTitle("JavaFX 2.0 WebView Example: Favorite Java Web Sites");
      final Group rootGroup = new Group();
      final Map<String,String> titleToUrl =
         ImmutableMap.<String,String>builder()
                     .put("Inspired by Actual Events", "http://marxsoftware.blogspot.com/")
                     .put("JavaWorld", "http://javaworld.com/")
                     .put("Java.net", "http://java.net/")
                     .put("Java Lobby", "http://javalobby.com/")
                     .build();
      rootGroup.getChildren().add(prepareAccordion(titleToUrl));
      final Scene scene = new Scene(rootGroup, 1000, 600, Color.WHITE);
      stage.setScene(scene);
      stage.show();
   }

   /**
    * Main function for running this JavaFX example.
    * 
    * @param arguments Command-line arguments: none expected.
    */
   public static void main(final String[] arguments)
   {
      Application.launch(arguments);
   }
}

In many ways, the above application works something like a stripped-down web browser. JavaFX does a lot of heavy lifting in processing the HTML source and presenting it just as a web browser would via WebView and an associated WebEngine. Some screen snapshots are shown next of how this application appears when it is run. The first image shows the application when it's initially loaded and the four screen snapshots following that one represent each of the four titled panes being clicked in the accordion.

The links within the presented HTML content can be clicked and the application supports traversal of links. However, significantly greater interaction between the JavaFX application and the rendered HTML can be accomplished using the methods on WebEngine that support interaction with JavaScript [such as getOnStatusChanged()]. The underlying document can also be accessed via WebEngine's documentProperty() and getDocument() methods.

With the increasing importance of HTML5, it's nice that JavaFX has built-in support for interacting with HTML, JavaScript, and the DOM.

1 comment:

@DustinMarx said...

Peter Zhelezniakov's post Communicating between JavaScript and JavaFX with WebEngine provides significant more details on communication between JavaFX and JavaScript.

Dustin