1 package JSci.swing; 2 3 import java.awt.*; 4 import JSci.awt.*; 5 10 public class JPieChart extends JCategoryGraph2D { 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 JPieChart(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=getWidth()/2; 73 origin.y=getHeight()/2; 74 redraw(); 75 } 76 79 protected void offscreenPaint(Graphics g) { 80 final int width=2*(origin.x-axisPad); 81 final int height=2*(origin.y-axisPad); 82 final double xRadius=0.4*width; 83 final double yRadius=0.4*height; 84 int angle=0; 86 model.firstSeries(); 87 final int n = model.seriesLength(); 88 if(n > 0) { 89 for(int i=0; i<n-1; i++) { 90 g.setColor(sliceColor[i]); 91 int arcAngle=Math.round(model.getValue(i)*360.0f/pieTotal); 92 g.fillArc(axisPad,axisPad,width,height,angle,arcAngle); 93 angle+=arcAngle; 94 } 95 g.setColor(sliceColor[n-1]); 96 g.fillArc(axisPad,axisPad,width,height,angle,360-angle); 97 } 98 g.setColor(getForeground()); 100 g.drawArc(axisPad,axisPad,width,height,0,360); 101 final int strHalfHeight=g.getFontMetrics().getHeight()/2; 103 double dAngle=0.0; 104 g.setColor(getForeground()); 105 for(int i=0; i<n; i++) { 106 double dHalfArcAngle=model.getValue(i)*Math.PI/pieTotal; 107 dAngle+=dHalfArcAngle; 108 String str = model.getCategory(i); 109 int strHalfWidth=g.getFontMetrics().stringWidth(str)/2; 110 g.drawString(str,origin.x-strHalfWidth+(int)(xRadius*Math.cos(dAngle)),origin.y+strHalfHeight-(int)(yRadius*Math.sin(dAngle))); 111 dAngle+=dHalfArcAngle; 112 } 113 } 114 } 115 | Popular Tags |