Academic Java    Java Tutorial  >  Graphics  >  pie arcs

pie arcs Example

Java pie arcs EXAMPLE output This applet creates a pie chart using random colors to represent a set of values held in an array.

An Arc2D.Float is used to draw each slice of the pie.

The shape classes have two forms, Float and Double. Each of these is an inner class of a parent class such as Arc2D.

Parameters of the constructor are double or float, as appropriate.
// 2D Graphic Shapes: Arc2D Example
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;

class Graphics2DExample2 extends JApplet {

   private int[] values = {50,60,90,130,142,225,317};
   private float total = 0;

   private Color randomColor() {
      return new Color(
         (int)(Math.random()*256),
         (int)(Math.random()*256),
         (int)(Math.random()*256)
      );
   }

   @Override public void init() {
      for(int i=0;i<values.length;++i) total+=values[i];
   }

   @Override public void paint(Graphics g) {
      super.paint(g);
      Graphics2D g2 = (Graphics2D)g;
      int x,y,w=getSize().width, h=getSize().height;
      w-=20; h-=100; x=10; y=50;
      float startAngle = 0;
      for (int i = 0; i < values.length; i++) {
         float angle = values[i] * 360f / total;
         Arc2D.Float slice = 
            new Arc2D.Float(x, y, w, h, startAngle, angle, Arc2D.PIE);
         g2.setColor(randomColor());
         g2.fill(slice);
         startAngle += angle;
      }
      g2.setColor(Color.black);
      g2.drawArc(x,y,w,h,0,360);
   }
}


* 2D shapes Examples