September 17, 2003

Pie Chart Applet (Version 2 with methods)

 



/*	Name: Deepak Kumar
File: PieChart.java
Purpose: Given the number of students in class that will major in
each discipline, depict the data as a pie chart.

Notes: Version 2

We have reorganized the applet by making use of various methods. Added another method called compute()...

*/
import java.awt.*;
   import java.applet.Applet;
public class PieChart extends Applet {
   // variables to store the number of students in each discipline
   int Sci, Soc, Hum;
   
   // variables to store percentages (should be float)
   float PercSci, PercSoc, PercHum;
   
   // the coordinates and size of the pie is fixed below
   int x = 50, y = 50, w = 100, h = 100;
   
   // these quantities will need to be computed for each slice
   int startAngle = 0, degrees;
   
   public void init() {
   
      // Set # of students in each discipline
      Sci = 5;
      Soc = 6;
      Hum = 7;
   
      compute();
   
   } // end of init
   
   private float perc(int x, int t) {
   
      return x * 100.0f/t;
   
   } // end of perc
   
   public void compute() {
   // the total number of students
      int Total;
   
      // Computer percentages
      Total = Sci + Soc + Hum;
   
      PercSci = perc(Sci, Total);
      PercSoc = perc(Soc, Total);
      PercHum = perc(Hum, Total);
   
      //PercSci = Sci * 100.0f / Total;
      //PercSoc = Soc * 100.0f / Total;
      //PercHum = Hum * 100.0f / Total;
   
      // Print out results for checking
      System.out.println("Total = " + Total);
      System.out.println("%Sci = " + PercSci);
      System.out.println("%Soc = " + PercSoc);
      System.out.println("%Hum = " + PercHum);
   
   } // end of compute
   
   
   public void paint(Graphics g) {
   
      // Display the Pie Chart
      // Display the Pie for Sciences
      degrees = (int) (PercSci*360/100);
      g.setColor(Color.red);
      g.fillArc(x, y, w, h, startAngle, degrees);
   
      // Pie for Soc
      startAngle = degrees;
      degrees = (int) (PercSoc*360/100);
      g.setColor(Color.yellow);
      g.fillArc(x, y, w, h, startAngle, degrees);
   
      // Pie for Hum
      startAngle = startAngle + degrees;
      degrees = (int) (PercHum*360/100);
      g.setColor(Color.green);
      g.fillArc(x, y, w, h, startAngle, degrees);
   
   } // end of paint
} // end of applet
Back to class exmaples | Back to CS110 Materials page