1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public void drawBarGraph(Graphics g, int[] vals, int w, int h) throws IllegalArgumentException
{
if (vals.length!=12) throw new IllegalArgumentException("There must be 12 months");
int mw=(w-30)/12;//width of each bar and 30px for labels;
int maxVal=0;
for (int loop=0 ; loop<vals.length ; loop++)
{
if (vals[loop]>maxVal) maxVal=vals[loop];//finds the biggest value cos this should reach top of graph;
}
float unit=h/maxVal;//number of pixels per unit;
g.setColor(Color.red);
for (int loop=0 ; loop<12 ; loop++)
{
g.fillRect(loop*mw+30, h-30-vals[loop]*unit, mw, vals[loop]*unit);//draw a bar;
}
g.setColor(Color.black);
g.drawLine(30, 0, 30, h-30);//x-axis line;
g.drawLine(30, h-30, w, h-30;//y-axis line;
//draw Labels;
}
public void paint(Graphics g)
{
drawBarGraph(g, vals, width, height); |
Partager