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.
Table of Contents
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.
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:
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;
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
}
});
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>
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" +
"FusionCharts.ready(function () {\n" +
" var revenueChart = new FusionCharts({\n" +
" type: 'doughnut2d',\n" +
" renderAt: 'chart-container',\n" +
" width: '450',\n" +
" height: '450',\n" +
" dataFormat: 'json',\n" +
" dataSource: {\n" +
" \"chart\": {\n" +
" \"caption\": \"Split of Revenue by Product Categories\",\n" +
" \"subCaption\": \"Last year\",\n" +
" \"numberPrefix\": \"$\",\n" +
" \"paletteColors\": \"#0075c2,#1aaf5d,#f2c500,#f45b00,#8e0000\",\n" +
" \"bgColor\": \"#ffffff\",\n" +
" \"showBorder\": \"0\",\n" +
" \"use3DLighting\": \"0\",\n" +
" \"showShadow\": \"0\",\n" +
" \"enableSmartLabels\": \"0\",\n" +
" \"startingAngle\": \"310\",\n" +
" \"showLabels\": \"0\",\n" +
" \"showPercentValues\": \"1\",\n" +
" \"showLegend\": \"1\",\n" +
" \"legendShadow\": \"0\",\n" +
" \"legendBorderAlpha\": \"0\",\n" +
" \"defaultCenterLabel\": \"Total revenue: $64.08K\",\n" +
" \"centerLabel\": \"Revenue from $label: $value\",\n" +
" \"centerLabelBold\": \"1\",\n" +
" \"showTooltip\": \"0\",\n" +
" \"decimals\": \"0\",\n" +
" \"captionFontSize\": \"14\",\n" +
" \"subcaptionFontSize\": \"14\",\n" +
" \"subcaptionFontBold\": \"0\"\n" +
" },\n" +
" \"data\": [\n" +
" {\n" +
" \"label\": \"Food\",\n" +
" \"value\": \"28504\"\n" +
" }, \n" +
" {\n" +
" \"label\": \"Apparels\",\n" +
" \"value\": \"14633\"\n" +
" }, \n" +
" {\n" +
" \"label\": \"Electronics\",\n" +
" \"value\": \"10507\"\n" +
" }, \n" +
" {\n" +
" \"label\": \"Household\",\n" +
" \"value\": \"4910\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }).render();\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" +
"FusionCharts.ready(function () {\n" +
" var revenueChart = new FusionCharts({\n" +
" type: 'doughnut2d',\n" +
" renderAt: 'chart-container',\n" +
" width: '450',\n" +
" height: '450',\n" +
" dataFormat: 'json',\n" +
" dataSource: {\n" +
" \"chart\": {\n" +
" \"caption\": \"Split of Revenue by Product Categories\",\n" +
" \"subCaption\": \"Last year\",\n" +
" \"numberPrefix\": \"$\",\n" +
" \"paletteColors\": \"#0075c2,#1aaf5d,#f2c500,#f45b00,#8e0000\",\n" +
" \"bgColor\": \"#ffffff\",\n" +
" \"showBorder\": \"0\",\n" +
" \"use3DLighting\": \"0\",\n" +
" \"showShadow\": \"0\",\n" +
" \"enableSmartLabels\": \"0\",\n" +
" \"startingAngle\": \"310\",\n" +
" \"showLabels\": \"0\",\n" +
" \"showPercentValues\": \"1\",\n" +
" \"showLegend\": \"1\",\n" +
" \"legendShadow\": \"0\",\n" +
" \"legendBorderAlpha\": \"0\",\n" +
" \"defaultCenterLabel\": \"Total revenue: $64.08K\",\n" +
" \"centerLabel\": \"Revenue from $label: $value\",\n" +
" \"centerLabelBold\": \"1\",\n" +
" \"showTooltip\": \"0\",\n" +
" \"decimals\": \"0\",\n" +
" \"captionFontSize\": \"14\",\n" +
" \"subcaptionFontSize\": \"14\",\n" +
" \"subcaptionFontBold\": \"0\"\n" +
" },\n" +
" \"data\": [\n" +
" {\n" +
" \"label\": \"Food\",\n" +
" \"value\": \"28504\"\n" +
" }, \n" +
" {\n" +
" \"label\": \"Apparels\",\n" +
" \"value\": \"14633\"\n" +
" }, \n" +
" {\n" +
" \"label\": \"Electronics\",\n" +
" \"value\": \"10507\"\n" +
" }, \n" +
" {\n" +
" \"label\": \"Household\",\n" +
" \"value\": \"4910\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }).render();\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);
}
}
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:
For both the methods, there are 2 separate buttons by which the chart can be rendered. Following is the output for the same:
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.
In case something went wrong and you are unable to see the chart, check for the following:
You can build complex web applications easily with Angular. But it’s a challenge to present…
JavaScript charts help transform raw data into clear, interactive visualizations that users can easily understand.…
Modern web applications depend on data visualization to transform complex information into clear, actionable insights.…
Data is a big part of modern software. Companies use charts to track sales, monitor…
Every day, businesses get more data than ever before. Looking at endless rows and columns…
Building interactive React charts from scratch can quickly become complicated. It becomes even more challenging…