JavaFX Tutorial - JavaFX WebView








JavaFX provides a GUI WebView (javafx.scene.web.WebView) node to render HTML5 content onto the Scene graph.

A WebView node is a mini-browser.

We can use the following code to load a web page and display it.

WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.load("http://mySite.com");

The full source code

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
//  w  w  w.j av a2s  . c  o m
public class Main extends Application {
  @Override
  public void start(final Stage stage) {
    stage.setWidth(400);
    stage.setHeight(500);
    Scene scene = new Scene(new Group());


    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();

    ScrollPane scrollPane = new ScrollPane();
    scrollPane.setContent(browser);

    webEngine.getLoadWorker().stateProperty()
        .addListener(new ChangeListener<State>() {
          @Override
          public void changed(ObservableValue ov, State oldState, State newState) {

            if (newState == Worker.State.SUCCEEDED) {
              stage.setTitle(webEngine.getLocation());
            }

          }
        });
    webEngine.load("http://java2s.com");

    scene.setRoot(scrollPane);

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

  public static void main(String[] args) {
    launch(args);
  }
}

The code above generates the following result.

null




WebEvents

JavaFX Web APIs also adhere to an event-driven programming model.

The following JavaScript in a web page will pop up an alert dialog box with a message from the browser window.

<script>
alert('JavaFX is  Awesome');
</script>

When the code is executed inside a JavaFX WebView node, a native dialog window will not pop up. However the OnAlert event gets raised as a javafx.scene.web.WebEvent object.

We can handle those events. To set up the handler, use the setOnAlert() method with an inbound parameter of type WebEvent.

    browser.getEngine().setOnAlert((WebEvent<String> wEvent) -> {
      System.out.println("Alert Event  -  Message:  " + wEvent.getData());
    });

The full source code

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
/*from w ww .  jav a 2 s. c o  m*/
public class Main extends Application {
  @Override
  public void start(final Stage stage) {
    stage.setWidth(400);
    stage.setHeight(500);
    Scene scene = new Scene(new Group());

    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();

    ScrollPane scrollPane = new ScrollPane();
    scrollPane.setContent(browser);

    browser.getEngine().setOnAlert((WebEvent<String> wEvent) -> {
      System.out.println("Alert Event  -  Message:  " + wEvent.getData());
    });

    webEngine.load("http://java2s.com");

    scene.setRoot(scrollPane);

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

  public static void main(String[] args) {
    launch(args);
  }
}

In the event handler we can decide if to show a dialog.

The following table shows the events and actions to trigger them from javafx.scene.web.WebEngine WebEvents and Properties.

Set On MethodOn Method PropertyDescription
setOnAlert()onAlertProperty()Handle JavaScript alert method
setOnError()onErrorProperty() WebEngine error handler
setOnResized()onResizedProperty()JavaScript resize handler
setOnStatusChanged()onStatusChanged()JavaScript status handler
setOnVisibilityChanged()onVisibilityChangedProperty() JavaScript window visibility handler
setConfirmHandler()confirmHandlerProperty()JavaScript Confirm window

The code above generates the following result.

null




Managing Web History

import javafx.application.Application;
import javafx.collections.ListChangeListener;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebHistory.Entry;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
//from  w w w.j  a  v  a2s .  c  om
public class Main extends Application {
  @Override
  public void start(final Stage stage) {
    stage.setWidth(400);
    stage.setHeight(500);
    Scene scene = new Scene(new Group());

    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();

    ScrollPane scrollPane = new ScrollPane();
    scrollPane.setContent(browser);

    browser.getEngine().setOnAlert((WebEvent<String> wEvent) -> {
      System.out.println("Alert Event  -  Message:  " + wEvent.getData());
    });

    webEngine.load("http://java2s.com");

    
    final WebHistory history = webEngine.getHistory();
    history.getEntries().addListener(new 
        ListChangeListener<WebHistory.Entry>() {
            @Override
            public void onChanged(Change<? extends Entry> c) {
                c.next();
                for (Entry e : c.getRemoved()) {
                    System.out.println(e.getUrl());
                }
                for (Entry e : c.getAddedSubList()) {
                    System.out.println(e.getUrl());
                }
            }
        }
    );
             
    history.go(0);
    scene.setRoot(scrollPane);

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

  public static void main(String[] args) {
    launch(args);
  }
}

The code above generates the following result.

null

Printing HTML Content

The following code shows how to print from a WebEngine.

    PrinterJob job = PrinterJob.createPrinterJob();
    if (job != null) {
        webEngine.print(job);
        job.endJob();
    }

Full source code

/*from   ww  w  . j a va 2s .c  om*/
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.print.PrinterJob;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class Main extends Application {
  @Override
  public void start(final Stage stage) {
    stage.setWidth(400);
    stage.setHeight(500);
    Scene scene = new Scene(new Group());

    VBox root = new VBox();

    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();

    ScrollPane scrollPane = new ScrollPane();
    scrollPane.setContent(browser);

    webEngine.getLoadWorker().stateProperty()
        .addListener(new ChangeListener<State>() {
          @Override
          public void changed(ObservableValue ov, State oldState, State newState) {
            if (newState == Worker.State.SUCCEEDED) {
              PrinterJob job = PrinterJob.createPrinterJob();
              if (job != null) {
                webEngine.print(job);
                job.endJob();
              }
            }
          }
        });
    webEngine.load("http://java2s.com");

    root.getChildren().addAll(scrollPane);
    scene.setRoot(root);

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

  public static void main(String[] args) {
    launch(args);
  }
}

Using WebView to display HTML

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
 /*www  .  j av a 2  s .  co m*/
public class Main extends Application {

    @Override
    public void start(Stage stage) {
        stage.setTitle("HTML");
        stage.setWidth(500);
        stage.setHeight(500);
        Scene scene = new Scene(new Group());

        VBox root = new VBox();     

        final WebView browser = new WebView();
        final WebEngine webEngine = browser.getEngine();

        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(browser);
        webEngine.loadContent("<b>asdf</b>");

        root.getChildren().addAll(scrollPane);
        scene.setRoot(root);

        stage.setScene(scene);
        stage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

Using CSS to change WebView background

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
 //w w w  .  jav  a 2s  .com
public class Main extends Application {

    @Override
    public void start(Stage stage) {
        stage.setTitle("HTML");
        stage.setWidth(500);
        stage.setHeight(500);
        Scene scene = new Scene(new Group());
    
        VBox root = new VBox();     
 
        final WebView browser = new WebView();
        final WebEngine webEngine = browser.getEngine();
        
     
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setStyle("-fx-background-color: white");
        
        scrollPane.setContent(browser);
        webEngine.loadContent("<b>asdf</b>");
         
        
        root.getChildren().addAll(scrollPane);
        scene.setRoot(root);
 
        stage.setScene(scene);
        stage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

The code above generates the following result.

null