Categories: Tutorials

Render Charts using FusionCharts and JavaFX

JavaFX is a software platform used to create and deliver desktop applications. With large set of built-in GUI components like text fields, webviews, buttons, tables and many more, it is very easy to create a desktop application using JavaFX. As this platform has support for almost all the operating systems (Microsoft Windows,Linux, macOS) it can run across a wide variety of devices. This tutorial will guide you on how you can render charts using FusionCharts and JavaFX. Let’s get started with the requirements and the steps mentioned below.

Prerequisites

Before we start with the requirements and steps to implement charts using FusionCharts and JavaFX, let’s first discuss about the essentials of user capabilities to implement it.
  • Must be familiar with the basic concepts of Java.
  • Must have a basic idea of how to create JavaFX application.
  • Must know the basics of HTML.

System Requirements

Creating Chart Object

To create a chart object, firstly, create a JavaFX application. Once the application has been created, create a Java class which will contain buttons and a webview. Use an event handler on the button, to show the chart as an output in the webview. Following are the step by step code snippets of .java code to create a chart object:

Step 1:

First, import all the packages required to create the application.
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.scene.control.Button;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import javafx.scene.web.WebEngine;
import javafx.scene.layout.VBox;
import javafx.scene.Scene;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

Step 2:

Create a button object, which on click will fire an event. The event will fetch the path of the external location of the file which in return will render the chart. Once done the chart will be displayed in the webview.
public class Fusioncharts_javafx extends Application {

    @Override
    public void start(Stage stage) throws Exception {
            WebView myWebView = new WebView();
            final WebEngine engine = myWebView.getEngine();



            Button btn1 = new Button("Render Chart from file");
            btn1.setOnAction(new EventHandler < ActionEvent > () {

                @Override
                public void handle(ActionEvent event) {

                    File currDir = new File(".");
                    String path = currDir.getAbsolutePath();
                    path = path.substring(0, path.length() - 1);
                    path = path.replaceAll("\\\\", "/");
                    // System.out.println(path);


                    File file = new File(path + "/src/fusioncharts_javafx/index.html");
                    URL url;
                    try {
                        url = file.toURI().toURL();
                        engine.load(url.toString());
                    } catch (MalformedURLException ex) {
                        Logger.getLogger(Fusioncharts_javafx.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    // file:/C:/test/a.html

                }
            });
  • Include FusionCharts library files which are required to render the chart.
  • To render the chart in the webview run the HTML file.
  • Create a button object, which on click will run the HTML file.
Following is the code of the chart to be rendered using the HTML file:
<html>

<head>
    <title>My first chart using FusionCharts Suite XT</title>
    <script type="text/javascript" src="fusioncharts.js"></script>
    <script type="text/javascript" src="fusioncharts.charts.js"></script>
    <script type="text/javascript">
        FusionCharts.ready(function() {
            var revenueChart = new FusionCharts({
                type: 'column2d',
                renderAt: 'chartContainer',
                width: '550',
                height: '350',
                dataFormat: 'json',
                dataSource: {
                    "chart": {
                        "caption": "Monthly revenue for last year",
                        "subCaption": "Harry's SuperMart",
                        "xAxisName": "Month",
                        "yAxisName": "Revenues (In USD)",
                        "numberPrefix": "$",
                        "paletteColors": "#0075c2",
                        "bgColor": "#ffffff",
                        "borderAlpha": "20",
                        "canvasBorderAlpha": "0",
                        "usePlotGradientColor": "0",
                        "plotBorderAlpha": "10",
                        "placevaluesInside": "1",
                        "rotatevalues": "1",
                        "valueFontColor": "#ffffff",
                        "showXAxisLine": "1",
                        "xAxisLineColor": "#999999",
                        "divlineColor": "#999999",
                        "divLineIsDashed": "1",
                        "showAlternateHGridColor": "0",
                        "subcaptionFontBold": "0",
                        "subcaptionFontSize": "14"
                    },
                    "data": [{
                            "label": "Jan",
                            "value": "420000"
                        },
                        {
                            "label": "Feb",
                            "value": "810000"
                        },
                        {
                            "label": "Mar",
                            "value": "720000"
                        },
                        {
                            "label": "Apr",
                            "value": "550000"
                        },
                        {
                            "label": "May",
                            "value": "910000"
                        },
                        {
                            "label": "Jun",
                            "value": "510000"
                        },
                        {
                            "label": "Jul",
                            "value": "680000"
                        },
                        {
                            "label": "Aug",
                            "value": "620000"
                        },
                        {
                            "label": "Sep",
                            "value": "610000"
                        },
                        {
                            "label": "Oct",
                            "value": "490000"
                        },
                        {
                            "label": "Nov",
                            "value": "900000"
                        },
                        {
                            "label": "Dec",
                            "value": "730000"
                        }
                    ],
                    "trendlines": [{
                        "line": [{
                            "startvalue": "700000",
                            "color": "#1aaf5d",
                            "valueOnRight": "1",
                            "displayvalue": "Monthly Target"
                        }]
                    }]
                }
            }).render();
        });
    </script>
</head>

<body>
    <div id="chartContainer">FusionCharts XT will load here! </div>
    <div>Loaded from a file</div>
</body>

</html>

Step 3:

To render the chart using the static string, pass the entire code as string to the engine.loadContent method. Refer to the following code for engine.loadContent method:
 Button btn2 = new Button("Render Chart from static string");
 btn2.setOnAction(new EventHandler  () {

     @Override
     public void handle(ActionEvent event) {
         engine.loadContent("\n" +
             "\n" +            
             "\n" +
             "\n" +
             "\n" +
             "\n" +
             "\n" +
             "  
FusionCharts XT will load here!
\n" + "
Loaded from a string
\n" + "\n" + ""); } }); VBox root = new VBox(); root.getChildren().addAll(myWebView, btn1, btn2); Scene scene = new Scene(root, 700, 510); stage.setScene(scene); stage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
The full java code for the sample looks as under:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.scene.control.Button;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import javafx.scene.web.WebEngine;
import javafx.scene.layout.VBox;
import javafx.scene.Scene;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class Fusioncharts_javafx extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        WebView myWebView = new WebView();
        final WebEngine engine = myWebView.getEngine();



        Button btn1 = new Button("Render Chart from file");
        btn1.setOnAction(new EventHandler  () {

            @Override
            public void handle(ActionEvent event) {

                File currDir = new File(".");
                String path = currDir.getAbsolutePath();
                path = path.substring(0, path.length() - 1);
                path = path.replaceAll("\\\\", "/");
                // System.out.println(path);


                File file = new File(path + "/src/fusioncharts_javafx/index.html");
                URL url;
                try {
                    url = file.toURI().toURL();
                    engine.load(url.toString());
                } catch (MalformedURLException ex) {
                    Logger.getLogger(Fusioncharts_javafx.class.getName()).log(Level.SEVERE, null, ex);
                }

                // file:/C:/test/a.html

            }
        });

        Button btn2 = new Button("Render Chart from static string");
        btn2.setOnAction(new EventHandler  () {

            @Override
            public void handle(ActionEvent event) {
                engine.loadContent("\n" +
                    "\n" +                   
                    "\n" +
                    "\n" +
                    "\n" +
                    "\n" +
                    "\n" +
                    "  
FusionCharts XT will load here!
\n" + "
Loaded from a string
\n" + "\n" + ""); } }); VBox root = new VBox(); root.getChildren().addAll(myWebView, btn1, btn2); Scene scene = new Scene(root, 700, 510); stage.setScene(scene); stage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }

Rendering the Chart

Now, the .java file is all set to run in your application. Any of the two buttons can be selected to render your chart using following two ways:
  • Using an External File
  • Using a Static String
For both the methods, there are 2 separate buttons by which the chart can be rendered. Following is the output for the same:

Rendering Chart using an External File

Rendering chart from a Static String

If you find any difficulty rendering the chart or with the configuration files, you can download this demo project from here and import it on your system.

Was There a Problem Rendering the Charts?

In case something went wrong and you are unable to see the chart, check for the following:
  • The chart ID should be unique for all charts rendered on the same page. Otherwise, it will result in a JavaScript error.
  • If the chart does not show up at all, check if the fusioncharts.js and FusionCharts wrapper FusionCharts.java was loaded. Also, check if the path to the fusioncharts.js and the FusionCharts.java files is correct, and whether the files exist in that location.
Ayan Bhadury and Dishank Tiwari

Recent Posts

Announcing FusionCharts v4.1: Elevate Your Data Visualization Experience!

We’re excited to announce the upcoming release of FusionCharts v4.1—a groundbreaking step forward in the…

5 days ago

Bubble Maps: Visualizing Data Like Never Before

Have you ever been overwhelmed by a massive data set and wondered, "How do I…

2 weeks ago

Stock Charts: Mastering the Art of Visualizing Financial Data

If you’ve ever tried to make sense of the stock market, you’ve probably come across…

4 weeks ago

What is a Bar Chart Used For?

Imagine you’re comparing the sales performance of your top product lines across different regions, or…

2 months ago

AI-Powered Documentation for Data Visualization & Analytics

Have you ever spent hours buried in documentation, hunting for a specific piece of code?…

3 months ago

Unveiling the Hidden Gems: Top 5 AI Data Visualization Tools for 2024

Do you feel like your data is a cryptic puzzle, locked away from revealing its…

4 months ago