Skip to main content

JavaFX WebView- Creating Browser Sample

Hi Friends,

In this post, i am going to give an overview about JavaFX WebView. This is an embedded browser component which is based on WebKit. If allow you to use Css, JavaScript, HTML5 and more to customise your embedded browser.

The embedded browser enables you to perform the following tasks in your JavaFX applications:
  • Render HTML content from local and remote URLs
  • Obtain Web history
  • Execute JavaScript commands
  • Perform upcalls from JavaScript to JavaFX
  • Manage web pop-up windows
  • Apply effects to the embedded browser 

I am going to provide and explain you a sample example to create your embedded browser. This is a JavaFX sample example. if you want to take an introduction about JavaFX please visit my previous blog.

I have use IntelliJ Idea IDE for this example. You can visit this link to understand how to create JavaFX application.

I am attaching the project structure image below-


In this sample- we have two java class.

First Main.java class, which is a launcher class extending Application.java class of JavaFx. 
Second BrowserController.java, which is controller class for browser view.

We have one FXML file named home-browser.fxml, which is browser user view.
We have a css file named progress.css to style the progress bar.

Main.java



package com.coderzduniya.sample.java;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.net.URL;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        //Loading launcher view
        final URL location = getClass().getResource("/resources/home-browser.fxml");
        final FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(location);
        fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
        final Parent root = fxmlLoader.load(location.openStream());
        //Creating scene
        Scene scene = new Scene(root);
        primaryStage.setTitle("CoderzDuniya Sample Browser");
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);
        primaryStage.setMaximized(false);
        //Showing application
        primaryStage.show();
    }


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

This Main.java class is the launcher class and this class is responsible to show view to user.


In this class we are loading home-browser.fxml file using FXMLLoader.


BrowserController.java




package com.coderzduniya.sample.java;

import javafx.concurrent.Worker;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextField;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

import java.net.URL;
import java.util.ResourceBundle;

public class BrowserController implements Initializable {


    @FXML
    WebView webView;
    private WebEngine webEngine;

    @FXML
    private Button btnGo;

    @FXML
    private TextField tvUrl;

    @FXML
    private ProgressBar progressBar;

    @Override
    public void initialize(URL url, ResourceBundle rb) {

        webEngine = webView.getEngine();
        // Removing right clicks
        webView.setContextMenuEnabled(false);
        //Setting button action
        btnGo.setOnAction((event -> loadWebsite()));
        // Updating progress bar using binding property
        progressBar.progressProperty().bind(webEngine.getLoadWorker().progressProperty());
        webEngine.getLoadWorker().stateProperty().addListener(
                (ov, oldState, newState) -> {
                    if (newState == Worker.State.SUCCEEDED) {
                        // Hide progress bar when page is ready
                        progressBar.setVisible(false);
                    } else {
                        //Showing progress bar
                        progressBar.setVisible(true);
                    }
                });
    }

    private void loadWebsite() {
        System.out.println("Loading your URL...");
        try {
            webEngine.load(tvUrl.getText());
        } catch (Exception e) {
            System.out.println("Url Problem:" + e.getCause().getMessage());
            e.printStackTrace();
        }
    }
}

This BrowserController.java class is an presenter class for home-browser.fxml file. This class fetch the entered url from the TextField of FXML and on click of Go button, loads the website onto webview.

home-browser.fxml




<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.*?>
<?import javafx.scene.web.*?>

<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.ProgressBar?>
<BorderPane prefHeight="550.0" prefWidth="900.0" xmlns="http://javafx.com/javafx/8"
            xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.coderzduniya.sample.java.BrowserController">
    <top>
        <VBox>
            <HBox prefHeight="27.0" prefWidth="Infinity" spacing="10">
                <padding>
                    <Insets topRightBottomLeft="10"/>
                </padding>
                <TextField fx:id="tvUrl" prefWidth="840.0"/>
                <Button fx:id="btnGo" text="Go" prefWidth="50.0"/>
            </HBox>
            <ProgressBar fx:id="progressBar" prefWidth="900.0" visible="false" stylesheets="@progress.css"/>
        </VBox>
    </top>
    <center>
        <WebView fx:id="webView" prefHeight="550.0" prefWidth="900.0"/>
    </center>
</BorderPane>

This home-browser.fxml is a view file Or you can say its an UI file of this browser.


progress.css




.progress-bar .bar {-fx-padding:1px; -fx-background-insets:0;}

This progress.css file is used to style the progress bar.


That's all for a simple browser application. Attaching application screenshots.






You can download full working sample example from GitHub from this link.

Hope this will help you. Suggestions are most welcome. Keep visiting my blog :)

Comments

Popular posts from this blog

Working with MPAndroidChart (how to create Bar Chart using MPAndroidChart)

Hi Friends, In this tutorial i am going to show, "How to create Bar Chart using MPAndroidChart". There is a lot of libraries for creating charts in android like AChartEngine, MpAndroidChart, AndroidPlot etc. Your first question may be, Why MPAndroidChart. So MpAndroidChart provides better animation functionality and easy to use in comparision. Using  MPAndroidChart library  we can draw a: ·          Simple Bar Chart ·          Grouped Bar Chart ·          Horizontal Bar Chart ·          Simple Line Chart ·          Line Chart with Cubic Lines ·          Grouped Line Chart ·          Combined Line and Bar Chart ·          Pie Chart ·          Scatter Chart ·          Candlestick Chart ·          Radar Chart Here we will create Simple Bar Chart with multiple color based on ranging. Ok We start with coding part now. First of all create your project in Android Studio and add gradle dependency for  MPAndroidChart library  into y

app-policy

PRIVACY POLICY Last updated April 19, 2023 This privacy notice for Team CoderzDuniya ( " Company ," " we ," " us ," or " our " ), describes how and why we might collect, store, use, and/or share ( " process " ) your information when you use our services ( " Services " ), such as when you: Download and use our mobile application ( Revenue Calculator) , or any other application of ours that links to this privacy notice Engage with us in other related ways, including any sales, marketing, or events Questions or concerns?  Reading this privacy notice will help you understand your privacy rights and choices. If you do not agree with our policies and practices, please do not use our Services. If you still have any questions or concerns, please contact us at droidamar007@gmail.com . SUMMARY OF KEY POINTS This summary provides key points from our privacy notice, but you can find out more details about any of these t