Java Swing is a powerful GUI toolkit for creating desktop applications. Among its many features, Swing provides a rich set of components for data visualization, including the JFreeChart library for creating charts and graphs. In this article, we'll explore how to create a pie chart using Java Swing and JFreeChart.

Before we dive into the code, let's ensure you have the necessary libraries. You'll need to add the JFreeChart library to your project. If you're using Maven, add this to your pom.xml file:

```xml
Setting Up the Environment
First, import the necessary classes and set up the JFrame for your application:

```java import javax.swing.*; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.data.general.DefaultPieDataset; public class PieChartExample extends JFrame { public PieChartExample() { super("Pie Chart Example"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(640, 480); } } ```
Creating the Pie Dataset
The first step in creating a pie chart is to create a dataset. JFreeChart provides the DefaultPieDataset class for this purpose:

```java DefaultPieDataset dataset = new DefaultPieDataset(); dataset.setValue("Category 1", new Double(45.0)); dataset.setValue("Category 2", new Double(25.0)); dataset.setValue("Category 3", new Double(30.0)); ```
Creating the Pie Chart
Next, use the ChartFactory to create the chart. You can customize the chart's title, legend, and tooltips:
```java JFreeChart chart = ChartFactory.createPieChart("Pie Chart Example", dataset, true, true, true); ```
Displaying the Chart

Now that you have your chart, you can display it in a JFrame using a ChartPanel:
```java ChartPanel chartPanel = new ChartPanel(chart); add(chartPanel); setVisible(true); ```
Here's the complete code for a simple pie chart:
```java import javax.swing.*; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.data.general.DefaultPieDataset; public class PieChartExample extends JFrame { public PieChartExample() { super("Pie Chart Example"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(640, 480); DefaultPieDataset dataset = new DefaultPieDataset(); dataset.setValue("Category 1", new Double(45.0)); dataset.setValue("Category 2", new Double(25.0)); dataset.setValue("Category 3", new Double(30.0)); JFreeChart chart = ChartFactory.createPieChart("Pie Chart Example", dataset, true, true, true); ChartPanel chartPanel = new ChartPanel(chart); add(chartPanel); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> new PieChartExample().setVisible(true)); } } ```
This example creates a simple pie chart with three categories. You can customize the chart further by changing the dataset values, colors, and other properties. Happy coding!



















