Kensoft PH
  • Download
    • KenshotApplication
  • Contact
  • About
Java Quiz
No Result
View All Result
Kensoft PH
  • Download
    • KenshotApplication
  • Contact
  • About
Java Quiz
No Result
View All Result
Kensoft PH
No Result
View All Result
Home Java

JavaFX WebView Tutorial | 100% best for beginners

October 24, 2021 - Updated on October 29, 2021
in Java, Downloads
Reading Time: 6 mins read
0
JavaFX WebView
1.8k
VIEWS
Share on FacebookShare on TwitterShare via Email

Contents

Toggle
  • JavaFX WebView Tutorial
  • How to use the WebView in JavaFX
    • Creating a web browser
    • Example 1: Displaying the content into JavaFX WebView
      • Output
    • Example 2: Succeed or Loading Failed
      • Output
    • Example 3: Loading the Progress bar
      • Output
    • Example 4: Reloading the page
      • Output
    • Example 5: Working on the Back and Forward Button
      • Output
    • Example 6: Zoom In and Zoom Out
      • Output
    • Example 7: Set the page title at the stage title
      • Output
    • Example 8: Set the URL at the textfield
      • Output
  • YouTube Video

JavaFX WebView Tutorial

JavaFX WebView is a web rendering engine. JavaFX provides a web component for embedding a web browser in a JavaFX application to display its web content like Kensoft PH, GeeksforGeeks, etc. If you want to learn how to make a web browser in JavaFX, this is the best tutorial for you to start learning and making a web browser in JavaFX. To begin learning, please read the entire article. We have provided best examples for you to learn from, and you can copy those codes below.

How to use the WebView in JavaFX

To display web content using the WebView in JavaFX, you must also have the WebEngine and WebHistory classes because the WebView uses the WebEngine for the core proecessing to display its content, in short the WebEngine is in charge of all HTML and JavaScript logic, while the WebHistory represents the web browsing history. 

The WebView handles user input such as mouse and keyboard events, as well as other tasks. The WebEngine will be used most of the time when you use the WebView component in your JavaFX application because the WebEngine maintains the browsing history of all visited web pages in an instance of the WebHistory class.

Creating a web browser

An instance of the WebView class represents a web browser. Please continue with the code below to create a WebView object.

WebView webview = new WebView();

We will need the WebEngine when we’ve created the webview object. The WebView class’s getEngine() method returns the WebEngine.

WebEngine engine = webview.getEngine();

To load content from a URL, use the load() method of the WebEngine class. You could use the reload() method to reload the current page if you wanted to. Check the code below to see what it looks like.

engine.load("https://www.google.com");
//Reload the current page
engine.reload();

There is another way to load content from a string. You could use the loadContent() method to load content in a String.

  • loadContent(String content)
  • loadContent(String content, String contentType)

This method is typically used when the content is retrieved from a database or creating the content in memory. Let’s assume in the following example is a “text/html” content type.

//loading the content
String html = "<html><head><title>Kensoft PH</title></head><body><p>Learn programming with Kensoft PH</p></body></html>";
engine.loadContent(html);

//or loading the content with plain text
String txt = "JavaFX WebView";
engine.load(txt, "text/plain");

Before we get started with our examples, you can download the JavaFX project that relates to the examples below and use it to learn at your convenience. Once you have downloaded the archive file, extract it and open the project in NetBeans IDE 12.3. This is a basic JavaFX web browser that showcases basic web browser functionality.

Download JavaFX Web Browser

In the following examples, we will learn and demonstrate how to create a simple web browser in a JavaFX application. We will go over loading content with the WebView in JavaFX and loading with a progress bar while the current page is still loading, as well as determining whether the URL has been loaded or loading failed. You will also learn how to go back and forward on the previous URL.

It is also very simple to learn how to zoom in and out of the content. Now, let us move on to our examples, which are based on the downloadable web browser project above.

Example 1: Displaying the content into JavaFX WebView

To load the webpage into our WebView, we’ll use a Textfield to enter the URL and a KeyPressed event to fire the URL and load the content into the WebView. So, when we press the ENTER key on the keyboard, the URL begins to load.

//I used a loadUrl() method
private void loadUrl() {
        engine = webview.getEngine();
        engine.load("https://" + txtFieldUrl.getText());
    }

//Key Pressed Event for Enter key
@FXML
    private void txtEnterKey(KeyEvent event) {
        if (event.getCode() == KeyCode.ENTER) {
            loadUrl();
        }
    }

Output

WebView in JavaFX

Example 2: Succeed or Loading Failed

In a web browser, identifying whether a page has been loaded or whether it has failed to load is also important. We’ll use the getLoadWorker() method to observe the change in the state of Worker by adding a listener to its State property, which represents the state.SUCCESSDED and state.FAILED.

engine.getLoadWorker().stateProperty().addListener((obs, oldValue, newValue) -> {
    if (newValue == Worker.State.SUCCEEDED) {
        System.out.println("Page has been loaded");
    } else if (newValue == Worker.State.FAILED) {
        System.out.println("Loading failed");
    }
});

Output

JavaFX WebView

Example 3: Loading the Progress bar

The concept of loading the progress bar is the same as in Example 2. To get the progress bar to work, we’ll use the bind() method, which connects the progress bar and the Worker, as well as the progressProperty() method, which represents the page loading progress.

progress.progressProperty().bind(engine.getLoadWorker().progressProperty());

Output

JavaFX WebView

Example 4: Reloading the page

To reload the JavaFX WebView content. You could use the WebEngine class’s reload() method.

@FXML
private void reload(ActionEvent event) {
    engine.reload();
}

Output

WebView in JavaFX

Example 5: Working on the Back and Forward Button

We will use the WebHistory class to go back and go forward. We will use the WebHistory class to go back and forward in time. The WebHistory class is used to navigate the WebEngine entry object to the location in the list of previously visited web pages.

// Forward button
@FXML
private void forward(ActionEvent event) {
    history = webview.getEngine().getHistory();
    history.go(1);
    ObservableList<WebHistory.Entry> entries = history.getEntries();
    txtFieldUrl.setText(entries.get(history.getCurrentIndex()).getUrl());
}

// Back Button
@FXML
private void back(ActionEvent event) {
    history = webview.getEngine().getHistory();
    history.go(-1);
    ObservableList<WebHistory.Entry> entries = history.getEntries();
    txtFieldUrl.setText(entries.get(history.getCurrentIndex()).getUrl());
}

Output

JavaFX WebView

Example 6: Zoom In and Zoom Out

To code the zoom function in JavaFX Webview is very easy and simple, we will the zoom property and the zoom property uses double value number. Changinng this property affects the entire content in JavaFX WebView. Here, we are zooming 10 percent of the WebView in JavaFX

@FXML
private void zoomIn(ActionEvent event) {
    webview.setZoom(webview.getZoom() + 0.10);
}

@FXML
private void zoomOut(ActionEvent event) {
    webview.setZoom(webview.getZoom() - 0.10);
}

Output

WebView in JavaFX

Example 7: Set the page title at the stage title

We can use the WebEngine or WebHistory to get the current web page title. The WebEngine is the simplest way to get the page title; however, the WebHistory is more complex than the WebEngine. The code below shows how to get the current web page title by using the WebEngine and WebHistory.

engine.getLoadWorker().stateProperty().addListener((obs, oldValue, newValue) -> {
    if (newValue == Worker.State.SUCCEEDED) {
        System.out.println("Page has been loaded");
        
        // This is how to get the page title using the WebHistory
        history = webview.getEngine().getHistory();
        ObservableList<WebHistory.Entry> entries = history.getEntries();
        
        //Since I am using to controller, I am going to code this way to access the stage
        Stage stage = (Stage) txtFieldUrl.getScene().getWindow();

        //Don't use the two lines of code below at the same time on getting the page title
        
        //Using the WebHistory to get the page title
        stage.setTitle(entries.get(history.getCurrentIndex()).getTitle());
        
        //Using the WebEngine to get the page title
        stage.setTitle(webview.getEngine().getTitle());

    } else if (newValue == Worker.State.FAILED) {
        System.out.println("Loading failed");
    }
});

Output

JavaFX WebView

Example 8: Set the URL at the textfield

We need the WebHistory class to get the page URL and set it on the Textfield. To get the page URL in JavaFX WebView, follow the example code below. Copy the code from Example 7 and add this code after getting the page title code.

txtFieldUrl.setText(entries.get(history.getCurrentIndex()).getUrl());

Output

WebView in JavaFX

YouTube Video

YouTube video
Tags: JavaFX WebViewJavaFX WebView TutorialWebView in JavaFX
Previous Post

JavaFX Effects Tutorial | 100% best for beginners

Next Post

Rank Math Pro Review – 100% Best SEO Plugin

KENSOFT

KENSOFT

What’s up! Kent is my name. The name KENSOFT is derived from the words Kent and Software. My programming language of choice is Java

Related tutorials

How to Use the JavaFX Pie Chart 100% For Beginners
Java

How to Use the JavaFX Pie Chart 100% For Beginners

June 12, 2024 - Updated on October 6, 2024
205
How to Connect to an API Using JavaFX
Java

How to Connect to an API Using JavaFX

May 26, 2024 - Updated on September 28, 2024
216
JavaFX SQLite Database CRUD Tutorial
Java

JavaFX SQLite Database CRUD Tutorial | Note Application

May 26, 2024 - Updated on September 28, 2024
590
Next Post
Rank Math Pro Review

Rank Math Pro Review - 100% Best SEO Plugin

JavaFX Mouse Events Tutorial – 100% Best For Beginners

JavaFX Mouse Events Tutorial - 100% Best For Beginners

JavaFX 17

How To install JDK 17 and JavaFX 17 on NetBeans IDE | Best

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tools

Multi-platform installer builder

Java profiler

  • Trending
  • Comments
  • Latest
MySQL database using XAMPP

How to connect Java to MySQL database using Xampp server | 100% best for beginners

October 27, 2020 - Updated on January 23, 2023
Failed to automatically set up a JavaFX Platform

Failed to automatically set up a JavaFX Platform SOLVED Apache NetBeans 12.3 | Best way

April 11, 2021 - Updated on July 3, 2022
JavaFX 17

How To install JDK 17 and JavaFX 17 on NetBeans IDE | Best

November 15, 2021 - Updated on December 13, 2021
hide and show password in jPasswordField

JPasswordField in Java Hide or Show Password | 100% best for beginners

April 2, 2021 - Updated on September 21, 2022
Failed to automatically set up a JavaFX Platform

Failed to automatically set up a JavaFX Platform SOLVED Apache NetBeans 12.3 | Best way

3DES in Java and AES in Java

How to use AES and 3DES in Java | 100% best for beginners

JavaFX Splash Screen

How to create JavaFX Splash Screen | 100% best for beginners

set up JavaFX and Scene Builder

How to set up JavaFX and Scene Builder in NetBeans IDE | 100% best for beginners

How to Use the JavaFX Pie Chart 100% For Beginners

How to Use the JavaFX Pie Chart 100% For Beginners

June 12, 2024 - Updated on October 6, 2024
How to Connect to an API Using JavaFX

How to Connect to an API Using JavaFX

May 26, 2024 - Updated on September 28, 2024
JavaFX SQLite Database CRUD Tutorial

JavaFX SQLite Database CRUD Tutorial | Note Application

May 26, 2024 - Updated on September 28, 2024
How to take a screenshot on PC using Kenshot

How to Take a Screenshot on PC Using Kenshot: A Full Guide

January 18, 2024 - Updated on October 6, 2024

Latest Tutorials

How to Use the JavaFX Pie Chart 100% For Beginners

How to Use the JavaFX Pie Chart 100% For Beginners

June 12, 2024 - Updated on October 6, 2024
How to Connect to an API Using JavaFX

How to Connect to an API Using JavaFX

May 26, 2024 - Updated on September 28, 2024
JavaFX SQLite Database CRUD Tutorial

JavaFX SQLite Database CRUD Tutorial | Note Application

May 26, 2024 - Updated on September 28, 2024

Popular Tutorials

  • MySQL database using XAMPP

    How to connect Java to MySQL database using Xampp server | 100% best for beginners

    0 shares
    Share 0 Tweet 0
  • Failed to automatically set up a JavaFX Platform SOLVED Apache NetBeans 12.3 | Best way

    0 shares
    Share 0 Tweet 0
  • How To install JDK 17 and JavaFX 17 on NetBeans IDE | Best

    0 shares
    Share 0 Tweet 0
Facebook Instagram Youtube Github LinkedIn Discord
Kensoft PH

What’s up! I'm Kent. The name KENSOFT is derived from the words Kent and Software. My programming language of choice is Java, which I use to create computer applications. In a company, I created applications and a website.

Categories

Website

Check the status

Privacy Policy

Terms and Condition

Sitemap

Latest Tutorials

How to Use the JavaFX Pie Chart 100% For Beginners

How to Use the JavaFX Pie Chart 100% For Beginners

June 12, 2024 - Updated on October 6, 2024
How to Connect to an API Using JavaFX

How to Connect to an API Using JavaFX

May 26, 2024 - Updated on September 28, 2024
JavaFX SQLite Database CRUD Tutorial

JavaFX SQLite Database CRUD Tutorial | Note Application

May 26, 2024 - Updated on September 28, 2024

© 2024 Made With Love By KENSOFT PH

No Result
View All Result
  • Download
    • Kenshot
  • Contact
  • About
  • Java Quiz

© 2024 Made With Love By KENSOFT PH

This website uses cookies. By continuing to use this website you are giving consent to cookies being used. Visit our Privacy and Cookie Policy.