Creating a pie chart with Highcharts

We will make a pie chart in this recipe. We will create Java server-side code that interacts with the Highcharts JavaScript library. More information about Highcharts can be found at http://www.highcharts.com.

The pie chart will display three answers for the question "Why Don't I Have a Girlfriend?".

Creating a pie chart with Highcharts

Getting ready

Download the Highcharts JavaScript library from http://www.highcharts.com/download.

How to do it...

Carry out the following steps to create a pie chart using Highcharts:

  1. Create a class named HighchartsState that extends JavaScriptComponentState. This class will be used as a transport box between Java and JavaScript.
    package com.packtpub.vaadin;
    
    import com.vaadin.shared.ui.JavaScriptComponentState;
    import org.json.JSONObject;
    
    public class HighchartsState extends JavaScriptComponentState {
    
      private JSONObject data;
    
      public JSONObject getData() {
        return data;
      }
    
      public void setData(JSONObject data) {
        this.data = data;
      }
    }
  2. Create a Highcharts class that will represent a Vaadin component that is able to communicate with JavaScript. We need to link this component with JavaScript files. We will do this by using the @JavaScript annotation from Vaadin as follows:
    @JavaScript({
      "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js",
      "http://code.highcharts.com/highcharts.js", "highcharts_connector.js" })
    public class Highcharts extends AbstractJavaScriptComponent {
    
      @Override
      public HighchartsState getState() {
        return (HighchartsState) super.getState();
      }
    
      public void setData(String jsonData) {
        try {
          JSONObject data = new JSONObject(jsonData);
          getState().setData(data);
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
    }
  3. Now we should add the code that displays the chart into the init method of the HighchartsUI class. We make JSON data as a pure string and set it to the Highcharts component.
    public class MyVaadinUI extends UI {
    
      @Override
      protected void init(VaadinRequest request) {
        VerticalLayout layout = new VerticalLayout();
                layout.setMargin(true);
                setContent(layout);
    
        String jsonData =
        "{" +
          "chart : " +
          "{renderTo : 'chart',}, " +
          "series : " +
          "[ " +
            "{" +
              "type : 'pie', " +
              "data : " +
              "[ " +
                "[ 'I'm average looking.', 2 ], " +
                "[ 'I'm shy around girls.', 3 ], " +
                "[ 'I'm level 80 Paladin.', 95 ] " +
              "] " +
            "} " +
          "] " +
       "}";
        Highcharts highchartsPie = new Highcharts();
    
        highchartsPie.setData(jsonData);
        highchartsPie.setId("chart");
        highchartsPie.setWidth("400px");
        highchartsPie.setHeight("300px");
    
        layout.addComponent(highchartsPie);
      }
    }
  4. We are about to send JSON data to the JavaScript chart. Therefore, we need to make a connection between Java and JavaScript. Make a new source folder named resources and create a com.packtpub.vaadin package in it. Create a new file named highcharts_connector.js and put the the following code into it:
    window.com_packtpub_vaadin_Highcharts = function() {
    
      this.onStateChange = function() {
        var chart = new Highcharts.Chart(this.getState().data);
      }
    }

Run the application and the pie chart appears in the browser.

How it works...

First, we create JSON data that we want to send to JavaScript. Then, we set the JSON data to the instance of the Highcharts class. This propagates the data to JavaScript via HighchartsState.

We have also set Id to chart on the highchartPie variable. This marks the HTML element so the chart library knows where to render the chart (renderTo : 'chart').

Inside the @JavaScript annotation, we have defined all the JavaScript libraries that need to be downloaded before the Highcharts can be used. We have added links to the libraries from the web, http://code.highcharts.com/highcharts.js for example. We should download the libraries and put them into the project folder, so the downloading does not depend on external websites.

@JavaScript({ "jquery.min.js", "highcharts.js", "highcharts_connector.js" })

The way we have passed the JSON data into the Highcharts chart can be used for all the charts contained in the Highcharts library.

See also

  • We do not have to implement all the charts by ourselves. Vaadin Charts is a paid add-on that uses the Highcharts library and contains many ready-made charts. More information about this add-on can be found at https://vaadin.com/add-ons/charts.