JavaFX

JavaFX WebView Example

Photo of Andreas PomarolliAndreas PomarolliOctober 13th, 2016Last Updated: April 24th, 2019
0 4,077 14 minutes read

This is a JavaFXWebView Example. JavaFX provides a web component that can be used as an embedded web browser in a JavaFX application. It is based on WebKit, which is an open source web browser engine. It supports:

  • Viewing HTML5 content with CSS and JavaScript
  • Access to the DOM of the HTML content
  • Browsing history maintenance
  • Executing JavaScript code from JavaFX and vice versa

The component handles most of the work of web browsing, for example, rendering the HTML content, maintaining a history of the visited web pages, navigating to a URL when links are clicked, displaying pop-up contents, among others.

 
The web browser component comprises a simple API consisting of a few classes in thejavafx.scene.web package:

  • WebView
  • WebEngine
  • WebHistory
  • WebHistory.Entry
  • WebEvent
  • PopupFeatures
  • PromptData

TheWebView class inherits from theParent class. It is a node, not a control. It is added to a Scene Graph for viewing web pages using local or remote URLs. AWebView displays one web page at a time and it can be styled using a CSS.

AWebView uses aWebEngine for the core processing of its content. AWebEngine manages one web page at a time. TheWebView handles user input events such as mouse and keyboard events and other tasks, for example, loading the web page content, applying a CSS, and creating a DOM, that are performed by theWebEngine. When using aWebView component, you will be working with itsWebEngine most of the time.

AWebEngine maintains the browsing history of all visited web pages for a session in an instance of theWebHistory class. An instance of the inner classWebHistory.Entry represents an entry in the browsing history. An instance of theWebEvent class represents an event generated by a WebEngine while it processes a web page.

The following table shows an overview of the whole article:

The following examples use Java SE 8 and JavaFX 2.2.

1. Creating a Web Browser Component

1.1 The Code

FxWebViewExample1.java

import javafx.beans.value.ChangeListener;import javafx.application.Application;import javafx.beans.value.ObservableValue;import javafx.scene.Scene;import javafx.scene.layout.VBox;import javafx.scene.web.WebView;import javafx.stage.Stage;import javafx.scene.web.WebEngine;import static javafx.concurrent.Worker.State;public class FxWebViewExample1 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(final Stage stage) {// Create the WebViewWebView webView = new WebView();// Create the WebEnginefinal WebEngine webEngine = webView.getEngine();// LOad the Start-PagewebEngine.load("http://www.oracle.com");// Update the stage title when a new web page title is availablewebEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {            public void changed(ObservableValue<? extends State> ov, State oldState, State newState)             {                if (newState == State.SUCCEEDED)                 {                    //stage.setTitle(webEngine.getLocation());                stage.setTitle(webEngine.getTitle());                }            }        });// Create the VBoxVBox root = new VBox();// Add the WebView to the VBoxroot.getChildren().add(webView);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add  the Scene to the Stagestage.setScene(scene);// Display the Stagestage.show();}}

An instance of theWebView class represents a web browser. The class contains only one constructor, which is a no-args constructor:

WebView webView = new WebView();

The constructor of theWebView class creates aWebEngine automatically and you cannot change it. ThegetEngine() method of theWebView class returns the reference of theWebEngine:

WebEngine webEngine = webView.getEngine();

AWebEngine can load content from a URL or a string in memory. You would use theload() method of theWebEngine class to load content from a URL. The URL is specified as a String. It can be a local or remote URL. You would use thereload() method of theWebEngine to reload the current page, as shown in the following code:

// Load the Google web pagewebEngine.load("http://www.oracle.com");

WebEngine loads a web page asynchronously in the background threads using aWorker object. Submitting a request to load a web page before the previous request is fulfilled cancels the previous request. You can find the reference of the Worker object loading the web page using thegetLoadWorker() method.

The following snippet of code sets the title of a successfully loaded web page as the title of the stage showing theWebView:

// Create the WebViewWebView webView = new WebView();// Create the WebEnginefinal WebEngine webEngine = webView.getEngine();

TheWebEngine class contains a title property, which is updated at some point while a web page is being loaded. You can achieve the same effect as above by listening to the change in the title property of theWebEngine:

// Update the stage title when a new web page title is availablewebEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {public void changed(ObservableValue<? extends State> ov, State oldState, State newState) {if (newState == State.SUCCEEDED) {    //stage.setTitle(webEngine.getLocation());stage.setTitle(webEngine.getTitle());}}});

1.2 The GUI

The following image shows how to use aWebView component. When you run the program, it opens the web page at http://www.oracle.com.

A simple JavaFX WebView Example
A simple JavaFX WebView Example

2. Setting Properties for a WebView

2.1 The Code

FxWebViewExample2.java

import javafx.beans.value.ChangeListener;import javafx.application.Application;import javafx.beans.value.ObservableValue;import javafx.scene.Scene;import javafx.scene.layout.VBox;import javafx.scene.text.FontSmoothingType;import javafx.scene.web.WebView;import javafx.stage.Stage;import javafx.scene.web.WebEngine;public class FxWebViewExample2 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(final Stage stage) {// Create the WebViewWebView webView = new WebView();// Disable the context menuwebView.setContextMenuEnabled(false);// Increase the text font size by 20%webView.setFontScale(1.20);// Set the Zoom 20%webView.setZoom(1.20);// Set font smoothing type to GRAYwebView.setFontSmoothingType(FontSmoothingType.GRAY);// Create the WebEnginefinal WebEngine webEngine = webView.getEngine();// Load the StartPagewebEngine.load("http://www.google.com");// Update the stage title when a new web page title is availablewebEngine.titleProperty().addListener(new ChangeListener<String>(){    public void changed(ObservableValue<? extends String> ov,            final String oldvalue, final String newvalue)     {    stage.setTitle(newvalue);    }});// Create the VBoxVBox root = new VBox();// Add the Children to the VBoxroot.getChildren().add(webView);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add  the Scene to the Stagestage.setScene(scene);// Display the Stagestage.show();}}

TheWebView component comes with some built-in features. By default, it displays a context menu. The menu items in the context menu depend on the state of the component.

For example, it shows a Go Back menu item when you have navigated to pages other than the first page and shows a Stop Loading menu item when the page is still being loaded. The standard text editing menu items (Cut, Copy, and Paste) are shown when text is selected or focus is in a text-editing field. You can set thecontextMenuEnabled property to false to disable the context menu:

// Disable the context menuwebView.setContextMenuEnabled(false);

You can apply a scale factor for text using thefontScale property. It uses a double value number. For example, to make the text font 10% larger, set it to 1.10, and to make the text font 40% smaller, set it to 0.60. The default value is 1.0. Changing this property affects only the text in the web page, not images and other fixed-size elements. The following code would increase the font by 20%:

// Increase the text font size by 20%webView.setFontScale(1.20);

You can apply a zoom factor to the content in theWebView using the zoom property. It also uses a double value number, as explained above. The default value is 1.0. changing this property affects the entire content inWebView. The following code would change the zoom by 20%:

// Zoom 20%webView.setZoom(1.20);

You can specify font smoothing of GRAY or LCD for onscreen text. The default value is LCD. The GRAY smoothing is suitable for graphics and animation. The LCD smoothing is suitable for small-sized text where legibility is important. A request for LCD text is treated as a hint, which may be ignored.

ThefontSmoothingType property specifies the font smoothing type. The property value is one of the constants (GRAY and LCD) of theFontSmoothingType enum, which is in thejavafx.scene.text package. The following code sets font smoothing:

// Set font smoothing type to GRAYwebView.setFontSmoothingType(FontSmoothingType.GRAY);

TheWebView class contains several other properties, which are related to setting its minimum, preferred, and maximum width and height.

2.2 The GUI

The following GUI shows an example of using properties in aWebView.

A JavaFX WebView Example with Properties
A JavaFX WebView Example with Properties

3. Enhancing the Web Browser Application

3.1 The Code

WebMenu.java

import javafx.beans.property.SimpleStringProperty;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.CheckMenuItem;import javafx.scene.control.Menu;import javafx.scene.control.MenuButton;import javafx.scene.control.MenuItem;import javafx.scene.control.RadioMenuItem;import javafx.scene.control.SeparatorMenuItem;import javafx.scene.control.ToggleGroup;import javafx.scene.text.FontSmoothingType;import javafx.scene.web.WebView;public class WebMenu extends MenuButton{public WebMenu(WebView webView) {// Set the Text of the WebMenuthis.setText("Options");// Set the Style-properties of the Navigation Barthis.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the Menu ItemsCheckMenuItem ctxMenu = new CheckMenuItem("Enable Context Menu");ctxMenu.setSelected(true);MenuItem normalFontMenu = new MenuItem("Normal");MenuItem biggerFontMenu = new MenuItem("10% Bigger");MenuItem smallerFontMenu = new MenuItem("10% Smaller");MenuItem normalZoomMenu = new MenuItem("Normal");MenuItem biggerZoomMenu = new MenuItem("10% Bigger");MenuItem smallerZoomMenu = new MenuItem("10% Smaller");// Create the RadioMenuItemsRadioMenuItem grayMenu = new RadioMenuItem("GRAY");grayMenu.setSelected(true);RadioMenuItem lcdMenu = new RadioMenuItem("LCD");// Create the MenusMenu scalingMenu = new Menu("Font Scale");scalingMenu.textProperty().bind(new SimpleStringProperty("Font Scale ").concat(webView.fontScaleProperty().multiply(100.0)).concat("%"));Menu smoothingMenu = new Menu("Font Smoothing");Menu zoomMenu = new Menu("Zoom");zoomMenu.textProperty().bind(new SimpleStringProperty("Zoom ").concat(webView.zoomProperty().multiply(100.0)).concat("%"));// Add  the Items to the corresponding MenuscalingMenu.getItems().addAll(normalFontMenu, biggerFontMenu, smallerFontMenu);smoothingMenu.getItems().addAll(grayMenu, lcdMenu);zoomMenu.getItems().addAll(normalZoomMenu, biggerZoomMenu, smallerZoomMenu);// Create the ToggleGroupnew ToggleGroup().getToggles().addAll(lcdMenu, grayMenu);// Define the Event HandlernormalFontMenu.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webView.setFontScale(1.0);}});biggerFontMenu.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webView.setFontScale(webView.getFontScale() + 0.10);}});smallerFontMenu.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webView.setFontScale(webView.getFontScale() - 0.10);}});grayMenu.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webView.setFontSmoothingType(FontSmoothingType.GRAY);}});lcdMenu.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webView.setFontSmoothingType(FontSmoothingType.LCD);}});normalZoomMenu.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webView.setZoom(1.0);}});biggerZoomMenu.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webView.setZoom(webView.getZoom() + 0.10);}});smallerZoomMenu.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webView.setZoom(webView.getZoom() - 0.10);}});webView.contextMenuEnabledProperty().bind(ctxMenu.selectedProperty());// Enabled JavaScript optionCheckMenuItem scriptMenu = new CheckMenuItem("Enable JavaScript");scriptMenu.setSelected(true);webView.getEngine().javaScriptEnabledProperty().bind(scriptMenu.selectedProperty());// Add Menus to the WebMenuthis.getItems().addAll(ctxMenu, scalingMenu, smoothingMenu, zoomMenu, new SeparatorMenuItem(), scriptMenu);}}

NavigationBar.java

import java.io.File;import java.net.MalformedURLException;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.TextField;import javafx.scene.layout.Priority;import javafx.scene.layout.HBox;import javafx.scene.web.WebEngine;import javafx.scene.web.WebView;import javafx.stage.FileChooser;import javafx.stage.FileChooser.ExtensionFilter;public class NavigationBar extends HBox{// Create the FileChooserprivate FileChooser fileChooser = new FileChooser();public NavigationBar(WebView webView, String homePageUrl, boolean goToHomePage) {// Set Spacingthis.setSpacing(4);// Set the Style-properties of the Navigation Barthis.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the LabelLabel label = new Label("History:");// Configure the FileChooserfileChooser.setTitle("Open Web Content");fileChooser.getExtensionFilters().addAll(new ExtensionFilter("HTML Files", "*.html", "*.htm"));// Create the WebEngineWebEngine webEngine = webView.getEngine();// Create the TextFieldTextField pageUrl = new TextField();// Create the ButtonsButton refreshButton = new Button("Refresh");Button goButton = new Button("Go");Button homeButton = new Button("Home");Button openButton = new Button("Open");// Let the TextField grow horizontalllyHBox.setHgrow(pageUrl, Priority.ALWAYS);// Add an ActionListener to navigate to the entered URLpageUrl.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webEngine.load(pageUrl.getText());}});// Update the stage title when a new web page title is availablewebEngine.locationProperty().addListener(new ChangeListener<String>(){    public void changed(ObservableValue<? extends String> ov,            final String oldvalue, final String newvalue)     {    // Set the Title of the Stage    pageUrl.setText(newvalue);    }});// Add an ActionListener for the Refresh ButtonrefreshButton.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webEngine.reload();}});// Add an ActionListener for the Go ButtongoButton.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webEngine.load(pageUrl.getText());}});// Add an ActionListener for the Home ButtonhomeButton.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){webEngine.load(homePageUrl);}});// Add an ActionListener for the Open ButtonopenButton.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){File selectedFile = fileChooser.showOpenDialog(webView.getScene().getWindow());if (selectedFile != null) {try {webEngine.load(selectedFile.toURI().toURL().toExternalForm());}catch(MalformedURLException ex) {ex.printStackTrace();}}}});// Add the Children to the Navigation Barthis.getChildren().addAll(label, pageUrl,goButton, refreshButton, homeButton, openButton);if (goToHomePage) {// Load the URLwebEngine.load(homePageUrl);}}}

FxWebViewExample3.java

Want to master JavaFX ?
Subscribe to our newsletter and download theJavaFXProgramming Cookbookright now!
In order to get you prepared for your JavaFX development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

import javafx.application.Application;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.scene.Scene;import javafx.scene.control.MenuButton;import javafx.scene.layout.VBox;import javafx.scene.web.WebView;import javafx.stage.Stage;public class FxWebViewExample3 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(final Stage stage) {// Create the WebViewWebView webView = new WebView();// Update the stage title when a new web page title is availablewebView.getEngine().titleProperty().addListener(new ChangeListener<String>(){    public void changed(ObservableValue<? extends String> ov,            final String oldvalue, final String newvalue)     {    // Set the Title of the Stage    stage.setTitle(newvalue);    }});// Load the Google web pageString homePageUrl = "http://www.google.com";// Create the WebMenuMenuButton menu = new WebMenu(webView);// Create the Navigation BarNavigationBar navigationBar = new NavigationBar(webView, homePageUrl, true);// Add the children to the Navigation BarnavigationBar.getChildren().add(menu);// Create the VBoxVBox root = new VBox(navigationBar, webView);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the Scene to the Stagestage.setScene(scene);// Display the Stagestage.show();}}

In the classFxWebViewExample1.java, you had a very basic web browser. Let’s enhance that browser to allow users to specify a URL and set options at runtime. The above class creates aWebOptionsMenu class for setting options for aWebView. It inherits from theMenuButton class. The constructor takes aWebView as an argument.

Now let’s create a reusable component for entering the URL of a new page. The code in the above Class creates a navigation bar. It boxes all the controls in anVBox. You need to pass theWebView for which the navigation will work, a home page URL, and a flag to indicate whether you want to navigate to the home page.

The buttons on the navigation bar have the following functions:

  • Enter a URL and press the Enter key to open the page or enter a URL and click the Go button to go to the page.
  • Click the Refresh button to reload the current page.
  • Click the Home button to go to the home page.
  • Click the Open button to open an HTML file from the local file system.

Enter a URL and press the Enter key to open the page or enter a URL and click the Go button to go to the page.

With theNavigationBar andWebMenu classes, you can develop a basic web browser writing a few lines of code. The program in the above class assembles the web browser components to build a basic web browser. It displays a window with a navigation bar, options, and aWebView. You would use the navigation bar to open any local or remote web page. Later you will enhance this program to show the browsing history and add Back and Forward buttons.

3.2 The GUI

The following image displays a window with a navigation bar, options, and aWebView. You would use the navigation bar to open any local or remote web page.

An enhanced JavaFX WebView Example
An enhanced JavaFX WebView Example

4. Accessing Browsing History

4.1 The Code

BrowserHistory.java

import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Button;import javafx.scene.control.ComboBox;import javafx.scene.control.Label;import javafx.scene.control.ListCell;import javafx.scene.control.ListView;import javafx.scene.layout.HBox;import javafx.scene.web.WebHistory;import javafx.scene.web.WebHistory.Entry;import javafx.scene.web.WebView;import javafx.util.Callback;public class BrowserHistory extends HBox{public BrowserHistory(WebView webView) {// Set Spacingthis.setSpacing(4);// Set the Style-properties of the Navigation Barthis.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the WebHistoryWebHistory history = webView.getEngine().getHistory();// Create the LabelLabel label = new Label("History:");// Create the ButtonsButton backButton = new Button("Back");backButton.setDisable(true);Button forwardButton = new Button("Forward");forwardButton.setDisable(true);// Add an ActionListener to the Back and Forward ButtonsbackButton.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){history.go(-1);}});forwardButton.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){history.go(1);}});// Add an ChangeListener to the currentIndex propertyhistory.currentIndexProperty().addListener(new ChangeListener<Number>(){    public void changed(ObservableValue<? extends Number> ov,            final Number oldvalue, final Number newvalue)     {int currentIndex = newvalue.intValue();if (currentIndex <= 0) {backButton.setDisable(true);} else {backButton.setDisable(false);}if (currentIndex >= history.getEntries().size()) {forwardButton.setDisable(true);} else {forwardButton.setDisable(false);}    }});// Create the ComboBox for the History ListComboBox<Entry> historyList = new ComboBox<>();historyList.setPrefWidth(150);historyList.setItems(history.getEntries());// Set a cell factory to to show only the page title in the history listhistoryList.setCellFactory(new Callback<ListView<WebHistory.Entry>, ListCell<WebHistory.Entry>>() {            @Override public ListCell<WebHistory.Entry> call(ListView<WebHistory.Entry> list)             {        ListCell<Entry> cell = new ListCell<Entry>()         {        @Override        public void updateItem(Entry item, boolean empty)         {        super.updateItem(item, empty);                if (empty)         {        this.setText(null);        this.setGraphic(null);        }         else         {        String pageTitle = item.getTitle();        this.setText(pageTitle);        }        }        };                return cell;                            }        });// Let the user navigate to a page using the history listhistoryList.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent event){int currentIndex = history.getCurrentIndex();Entry selectedEntry = historyList.getValue();int selectedIndex = historyList.getItems().indexOf(selectedEntry);int offset = selectedIndex - currentIndex;history.go(offset);}});// Add the Children to the BrowserHistorythis.getChildren().addAll(backButton, forwardButton, label,historyList);}}

FxWebViewExample4.java

import javafx.beans.value.ChangeListener;import javafx.application.Application;import javafx.beans.value.ObservableValue;import javafx.scene.Scene;import javafx.scene.control.MenuButton;import javafx.scene.layout.VBox;import javafx.scene.web.WebView;import javafx.stage.Stage;public class FxWebViewExample4 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(final Stage stage) {// Create the WebViewWebView webView = new WebView();// Update the stage title when a new web page title is availablewebView.getEngine().titleProperty().addListener(new ChangeListener<String>(){    public void changed(ObservableValue<? extends String> ov,            final String oldvalue, final String newvalue)     {    // Set the Title of the Stage    stage.setTitle(newvalue);    }});// Load the Google web pageString homePageUrl = "http://www.google.com";// Create the WebMenuMenuButton menu = new WebMenu(webView);// Create the Browser HistoryBrowserHistory history = new BrowserHistory(webView);// Create the Navigation BarNavigationBar navigationBar = new NavigationBar(webView, homePageUrl, true);// Add the Children to the Navigation BarnavigationBar.getChildren().addAll(menu,history);// Create the VBoxVBox root = new VBox(navigationBar, webView);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the Scene to the Stagestage.setScene(scene);// Display the Stagestage.show();}}

TheWebEngine maintains the browsing history for a session. An instance of theWebHistory class represents the browsing history, which maintains an observable list of visited web pages as instances of the inner classWebHistory.Entry. You would use thegetHistory() method of theWebEngine class to get its history object. ThegetEntries() method of aWebHistory returns anObservableList<Entry>. The entries in the list are arranged from oldest to newest, that is, the first entry in the list is the page visited first.

An Entry provides the title, URL, and the last visited date of the visited page through itsgetTitle(),getUrl(), andgetLastVisitedDate() methods, respectively.

WebHistory has two properties:

  • currentIndex
  • maxSize

ThecurrentIndex is a read-only int property that specifies the index of the current page in the list of visited pages. It changes as you visit different pages. ThemaxSize property specifies how many visited pages to keep in the history. The default is 100.

Thego(int offset) method of theWebHistory class navigates theWebEngine to the Entry object at the(currentIndex + offset) location in the list of visited web pages. For example,go(-1) andgo(1) have the same effect as clicking the Back and Forward buttons, respectively, in a web browser. Thego(0) call is ignored. The offset value must be between zero and(size - 1), which is the size of the number of entries in theWebHistory. Otherwise, anIndexOutOfBoundsException is thrown.

The following snippet of code shows how to add the history-related controls to the navigation bar.

// Create the WebMenuMenuButton menu = new WebMenu(webView);// Create the Browser HistoryBrowserHistory history = new BrowserHistory(webView);// Create the Navigation BarNavigationBar navigationBar = new NavigationBar(webView, homePageUrl, true);// Add the Children to the Navigation BarnavigationBar.getChildren().addAll(menu,history);

4.2 The GUI

The following GUI shows aWebView with a browser history:

A JavaFX WebView Example with History
A JavaFX WebView Example with History

5. Download

This was an example ofjavafx.scene.web.WebView

Download
You can download the full source code of this example here:JavaFxWebViewExample.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Andreas PomarolliAndreas PomarolliOctober 13th, 2016Last Updated: April 24th, 2019
0 4,077 14 minutes read
Photo of Andreas Pomarolli

Andreas Pomarolli

Andreas has graduated from Computer Science and Bioinformatics at the University of Linz. During his studies he has been involved with a large number of research projects ranging from software engineering to data engineering and at least web engineering. His scientific focus includes the areas of software engineering, data engineering, web engineering and project management. He currently works as a software engineer in the IT sector where he is mainly involved with projects based on Java, Databases and Web Technologies.

Related Articles

The JavaFX Print API

July 8th, 2016

JavaFX Canvas Example

May 18th, 2016

JavaFX CSS Tutorial

May 5th, 2016

The JavaFX Media API

August 8th, 2016

JavaFX 2D Shape Example

October 21st, 2016
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.