1 package JSci.awt; 2 3 import java.awt.*; 4 5 10 public class PieChart extends CategoryGraph2D { 11 14 private float pieTotal; 15 18 protected Color sliceColor[]={Color.blue,Color.green,Color.red,Color.yellow,Color.cyan,Color.lightGray,Color.magenta,Color.orange,Color.pink}; 19 22 public PieChart(CategoryGraph2DModel cgm) { 23 super(cgm); 24 dataChanged(new GraphDataEvent(model)); 25 } 26 30 public void dataChanged(GraphDataEvent e) { 31 model.firstSeries(); 32 final int len=model.seriesLength(); 33 pieTotal=0.0f; 34 for(int i=0;i<len;i++) 35 pieTotal+=model.getValue(i); 36 if(len>sliceColor.length) { 37 Color tmp[]=sliceColor; 38 sliceColor=new Color[len]; 39 System.arraycopy(tmp,0,sliceColor,0,tmp.length); 40 for(int i=tmp.length;i<sliceColor.length;i++) 41 sliceColor[i]=sliceColor[i-tmp.length]; 42 } 43 rescale(); 44 } 45 50 public final void setColor(int n,Color c) { 51 sliceColor[n]=c; 52 } 53 57 public final Color getColor(int n) { 58 return sliceColor[n]; 59 } 60 63 public final void setBounds(int x,int y,int width,int height) { 64 super.setBounds(x,y,width,height); 65 rescale(); 66 } 67 70 protected final void rescale() { 71 origin.x=getSize().width/2; 72 origin.y=getSize().height/2; 73 redraw(); 74 } 75 78 protected void offscreenPaint(Graphics g) { 79 final int width=2*(origin.x-axisPad); 80 final int height=2*(origin.y-axisPad); 81 final double xRadius=0.4*width; 82 final double yRadius=0.4*height; 83 int angle=0; 85 model.firstSeries(); 86 final int n = model.seriesLength(); 87 if(n > 0) { 88 for(int i=0; i<n-1; i++) { 89 g.setColor(sliceColor[i]); 90 int arcAngle=Math.round(model.getValue(i)*360.0f/pieTotal); 91 g.fillArc(axisPad,axisPad,width,height,angle,arcAngle); 92 angle+=arcAngle; 93 } 94 g.setColor(sliceColor[n-1]); 95 g.fillArc(axisPad,axisPad,width,height,angle,360-angle); 96 } 97 g.setColor(getForeground()); 99 g.drawArc(axisPad,axisPad,width,height,0,360); 100 final int strHalfHeight=g.getFontMetrics().getHeight()/2; 102 double dAngle=0.0; 103 g.setColor(getForeground()); 104 for(int i=0; i<n; i++) { 105 double dHalfArcAngle=model.getValue(i)*Math.PI/pieTotal; 106 dAngle+=dHalfArcAngle; 107 String str = model.getCategory(i); 108 int strHalfWidth=g.getFontMetrics().stringWidth(str)/2; 109 g.drawString(str,origin.x-strHalfWidth+(int)(xRadius*Math.cos(dAngle)),origin.y+strHalfHeight-(int)(yRadius*Math.sin(dAngle))); 110 dAngle+=dHalfArcAngle; 111 } 112 } 113 } 114 | Popular Tags |