Data Access‎ > ‎

Data Charts


Starting with version 1.2 of the SDK, JavaFX introduced built-in data visualization components, located in javafx.scene.chart,  that let developers easily create charts of all sorts.  The API offers support for more than half a dozen chart types. All charts, however, share a common implementation design which makes the creation of all charts a similar exercise.  Below is an example of how to create a bar chart.

First we define the data in a sequence of Barchart.Series data structure:

var cats = ["Q32009", "Q32008"];

var dataSeries = [
    BarChart.Series {
        name: "Nokia"
        data: [
            BarChart.Data {category: cats[0] value: 16.1},
            BarChart.Data {category: cats[1] value: 15.4}
        ]
    },
    BarChart.Series {
        name: "RIM"
        data: [
            BarChart.Data {category: cats[0] value: 8.5},
            BarChart.Data {category: cats[1] value: 5.8}
        ]
    },
    BarChart.Series {
        name: "Apple"
        data: [
            BarChart.Data {category: cats[0] value: 7},
            BarChart.Data {category: cats[1] value: 4.7}
        ]
    },
    BarChart.Series {
        name: "HTC"
        data: [
            BarChart.Data {category: cats[0] value: 2.7},
            BarChart.Data {category: cats[1] value: 1.7}
        ]
    },
    BarChart.Series {
        name: "Samsung"
        data: [
            BarChart.Data {category: cats[0] value: 1.3},
            BarChart.Data {category: cats[1] value: 1.1}
        ]
    },
    BarChart.Series {
        name: "Others"
        data: [
            BarChart.Data {category: cats[0] value: 5.4},
            BarChart.Data {category: cats[1] value: 7.8}
        ]
    }
];

Next we add an instance of BarChart to the scene graph using the data defined above:

Stage {
  title: "Smartphone Sales"
  scene: Scene {
    content: [
      BarChart {
        title: "Smartphone Sales"
        titleFont: Font { size: 24 }
        categoryAxis:CategoryAxis {
            categories:cats
        }
        valueAxis:NumberAxis{
            label:"Sales (100K)"
            upperBound:20
            lowerBound:0
        }

        data: bind dataSeries
      }
    ]
  }
}

Once the application is executed, it produces the chart shown below:


The materials on this website represent a small sample of content loosely based on the book JavaFX Application Development Cookbook.  The book offers far more content with over 80 recipes covering a range of topics from basics to advanced concepts.  

Buy the Book

You can get your copy of the book directly from the publisher. Click here to order!