Drawing a Pie Chart - Java 2D Graphics

Java examples for 2D Graphics:Arc

Description

Drawing a Pie Chart

Demo Code


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class Main {

  public void main(String[] argv) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new MyComponent());
    frame.setSize(300, 200);//w  w w  . jav  a2 s.com
    frame.setVisible(true);
  }

}

class MyComponent extends JComponent {
  PieValue[] slices = new PieValue[4];

  MyComponent() {
    slices[0] = new PieValue(25, Color.red);
    slices[1] = new PieValue(33, Color.green);
    slices[2] = new PieValue(20, Color.pink);
    slices[3] = new PieValue(15, Color.blue);
  }

  public void paint(Graphics g) {
    // Draw the pie
    drawPie((Graphics2D) g, getBounds(), slices);
  }

  public void drawPie(Graphics2D g, Rectangle area, PieValue[] slices) {
    double total = 0.0D;
    for (int i = 0; i < slices.length; i++) {
      total += slices[i].value;
    }
    double curValue = 0.0D;
    int startAngle = 0;
    for (int i = 0; i < slices.length; i++) {
      // Compute the start and stop angles
      startAngle = (int) (curValue * 360 / total);
      int arcAngle = (int) (slices[i].value * 360 / total);

      if (i == slices.length - 1) {
        arcAngle = 360 - startAngle;
      }

      g.setColor(slices[i].color);
      g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);

      curValue += slices[i].value;
    }
  }
}

class PieValue {
  double value;
  Color color;

  public PieValue(double value, Color color) {
    this.value = value;
    this.color = color;
  }
}

Related Tutorials