KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JSci > swing > JStackedBarGraph


1 package JSci.swing;
2
3 import java.awt.*;
4 import JSci.awt.*;
5
6 /**
7 * A stacked bar graph Swing component.
8 * Multiple series are stacked.
9 * @version 1.2
10 * @author Lindsay Laird
11 */

12 public class JStackedBarGraph extends JBarGraph {
13         /**
14         * Constructs a stacked bar graph.
15         */

16         public JStackedBarGraph(CategoryGraph2DModel gm) {
17                 super(gm);
18         }
19         /**
20         * Implementation of GraphDataListener.
21         * Application code will not use this method explicitly, it is used internally.
22         */

23         public void dataChanged(GraphDataEvent e) {
24                 float tmp;
25                 minY=0.0f;
26                 maxY=Float.NEGATIVE_INFINITY;
27                 model.firstSeries();
28                 for(int i=0;i<model.seriesLength();i++) {
29                         tmp=model.getValue(i);
30                         while(model.nextSeries())
31                                 tmp+=model.getValue(i);
32                         minY=Math.min(tmp,minY);
33                         maxY=Math.max(tmp,maxY);
34                         model.firstSeries();
35                 }
36                 if(minY==maxY) {
37                         minY-=0.5f;
38                         maxY+=0.5f;
39                 }
40                 setNumbering(numbering);
41         }
42         /**
43         * Draws the graph bars.
44         */

45         protected void drawBars(Graphics g) {
46 // bars
47
int dy,totalDy;
48                 for(int i=0;i<model.seriesLength();i++) {
49                         model.firstSeries();
50                         dy = drawStackedBar(g, i, model.getValue(i), barColor[0], 0);
51                         totalDy=dy;
52                         for(int n=1;model.nextSeries();n++) {
53                                 dy = drawStackedBar(g, i, model.getValue(i), barColor[n], -totalDy);
54                                 totalDy+=dy;
55                         }
56                 }
57         }
58         /**
59         * Draws a bar.
60         * @return the height of the bar.
61         */

62         private int drawStackedBar(Graphics g, int pos, float value, Color color, int yoffset) {
63                 Point p;
64                 if(value<0.0f)
65                         p=dataToScreen(pos,0.0f);
66                 else
67                         p=dataToScreen(pos,value);
68                 g.setColor(color);
69                 final int dy=Math.abs(p.y-origin.y);
70                 g.fillRect(p.x+barPad, p.y+yoffset, barWidth, dy);
71                 g.setColor(Color.black);
72                 g.drawRect(p.x+barPad, p.y+yoffset, barWidth, dy);
73                 return dy;
74         }
75 }
76
77
Popular Tags