Creating pie charts

The following pie chart example is based on the 2000 population of selected European countries as summarized here:

Country

Population

Percentage

Belgium

10,263,618

3

France

61,137,000

26

Germany

82,187,909

35

Netherlands

15,907,853

7

Sweden

8,872,000

4

United Kingdom

59,522,468

25

The JavaFX implementation uses the same Application base class and main method as used in the previous examples. We will not use a separate method for creating the GUI, but instead place this code in the start method, as shown here:

public class PieChartSample extends Application { 
 
    public void start(Stage stage) { 
        Scene scene = new Scene(new Group()); 
        stage.setTitle("Europian Country Population"); 
        stage.setWidth(500); 
        stage.setHeight(500); 
        ... 
    } 
 
    public static void main(String[] args) { 
        launch(args); 
    } 
     
} 

A pie chart is represented by the PieChart class. We can create and initialize the pie chart in the constructor by using an ObservableList of pie chart data. This data consists of a series of PieChart.Data instances, each containing a text label and a percentage value.

The next sequence creates an ObservableList instance based on the European population data presented earlier. The FXCollections class's observableArrayList method returns an ObservableList instance with a list of pie chart data:

ObservableList<PieChart.Data> pieChartData = 
        FXCollections.observableArrayList( 
        new PieChart.Data("Belgium", 3), 
        new PieChart.Data("France", 26), 
        new PieChart.Data("Germany", 35), 
        new PieChart.Data("Netherlands", 7), 
        new PieChart.Data("Sweden", 4), 
        new PieChart.Data("United Kingdom", 25)); 

We then create the pie chart and set its title. The pie chart is then added to the scene, the scene is associated with the stage, and then the window is displayed:

final PieChart pieChart = new PieChart(pieChartData); 
pieChart.setTitle("Country Population"); 
((Group) scene.getRoot()).getChildren().add(pieChart); 
stage.setScene(scene); 
stage.show(); 

When the application is executed, the following graph is displayed:

Creating pie charts
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.237.201