51 JavaFX PieChart
The JavaFX PieChart component is capable of drawing pie charts in your JavaFX application based on data you supply it. The PieChart component is really easy to use. The JavaFX PieChart component is represented by the class javafx.scene.chart.PieChart
.
Creating a PieChart
You create a JavaFX PieChart component by creating an instance of the PieChart
class. Here is a JavaFX PieChart
instantiation example:
PieChart pieChart = new PieChart();
Adding Data to a PieChart
To display anything you must add data to the PieChart
. Pie chart data is represented by the PieChart.Data
class. Each slice in the pie chart is represented by one PieChart.Data
instance. Here is an example of adding data to a JavaFX PieChart
component:
PieChart pieChart = new PieChart(); PieChart.Data slice1 = new PieChart.Data("Desktop", 213); PieChart.Data slice2 = new PieChart.Data("Phone" , 67); PieChart.Data slice3 = new PieChart.Data("Tablet" , 36); pieChart.getData().add(slice1); pieChart.getData().add(slice2); pieChart.getData().add(slice3);
Adding a PieChart to the Scene Graph
In order to make a JavaFX PieChart
component visible it must be added to the JavaFX scene graph. This means adding the PieChart
instance to a Scene
object, or adding it to a layout component which is added to a Scene
object.
Here is a full example of adding a PieChart
to the JavaFX scene graph:
package com.jenkov.javafx.charts; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.chart.PieChart; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class PieChartExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("My First JavaFX App"); PieChart pieChart = new PieChart(); PieChart.Data slice1 = new PieChart.Data("Desktop", 213); PieChart.Data slice2 = new PieChart.Data("Phone" , 67); PieChart.Data slice3 = new PieChart.Data("Tablet" , 36); pieChart.getData().add(slice1); pieChart.getData().add(slice2); pieChart.getData().add(slice3); VBox vbox = new VBox(pieChart); Scene scene = new Scene(vbox, 400, 200); primaryStage.setScene(scene); primaryStage.setHeight(300); primaryStage.setWidth(1200); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } }
The application resulting from running the above code would look similar to this: