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

Java Socket Basics(Socket Programming in Java) Part-2(UDP)

Hi friends, We are going to discuss about UDP Socket Programming . In previous post  we discussed about the differences between TCP & UDP and the sample example of TCP Socket Programming. Below is the sample example of chat application using UDP  Socket Programming . UDP Sample :-  We are going to create an small example which contains two classes. UdpServer.java:-  This is a server class. Means this class will serve the purpose of socket connection. DatagramSocket is the java class and serve the purpose of Server and Client both. The overloaded constructor of DatagramSocket class matters. DatagramPacket is the java class which is responsible to transmit the data/packet over the network from server to client and vice-versa. UdpClient.java:-  This is client class. This serves the purpose of client which will communicate to server and send data to server and receive the data sent by server. UdpServer.java import java.net.DatagramPacket ; import java.net.Datag