/////// PiePlot.java /////// import java.awt.*; /** Draws a color pie chart given: n: the number of items perc: n percentages (must sum to 1) c: n colors to use */ class PiePlot extends Canvas { public PiePlot(int n, double[] perc, Color[] c) { items = n; color = c; ang0 = new int[n]; ang1 = new int[n]; int start=0; for (int i=0; i < items; i++) { if ( start >= 360 ) break; ang0[i] = start; ang1[i] = Math.max(2, (int)(360*perc[i]+0.5)); if ( start + ang1[i] > 360 ) ang1[i] = 360 - start; start += ang1[i]; } } protected PiePlot() { } public void paint(Graphics g) // override { int wd = getSize().width; int ht = getSize().height; w = wd*4/5; h = (int)(w*ratio); if ( h > ht - 12 ) { h = ht - 12; w = (int)(h/ratio); } x0 = ( wd - w )/4; // left margin y0 = ht - h; // headroom for (int i=0; i < items; i++) { g.setColor(color[i]); g.fillArc(x0, y0, w, h, ang0[i], ang1[i]); } } protected int items; // no of sections protected Color[] color; // section colors protected int[] ang0; // starting angles protected int[] ang1; // section angles protected int x0=0, y0=0, w=0, h=0; // area for oval pie protected double ratio = 0.62; // golden ratio }