// // BarChart.java - defines BarChart class // // Code Developed for the Java Tutor column in Java Report // and Datamation Magazine // // Copyright (c) 1995 by Philip Meese // package ThirdParty.BarChart; import java.awt.*; // referece to the Abstract Window Toolkit pkg import ThirdParty.BarChart.*; // ref to our own class public class BarChart extends Canvas { // member data NumericSet _set; Rectangle _rect; // our getBounds (bounding rectangle) int _margin=5; // for t, b, l and r margins // member functions public BarChart(NumericSet set_, int width_, int height_){ numericSet(set_); setBounds(0, 0, width_, height_); } public void numericSet(NumericSet set_){ _set=set_; repaint(); } public void paint(Graphics g_){ _rect=getBounds(); paintBackground(g_, Color.white); if(_set.length()>0) paintBars(g_); } public void paintBars(Graphics g_){ int sep=2; // interbar spacing Color c=g_.getColor(); // remember color for later // area within which the bars will be rendered int renderWidth=_rect.width-_margin*2-(_set.length()-1)*sep; int renderHeight=_rect.height-_margin*2; int barWidth=renderWidth/_set.length(); // scaling factor so values fit in given height float scaleFactor=(float)renderHeight/_set.max(); Point barOrg=new Point(_margin, _margin); for(int i=0; i<_set.length(); i++, barOrg.y=_margin){ int barHeight=(int)(_set.value(i)*scaleFactor); // adjust bar rect so it grows from bottom barOrg.y=_margin+renderHeight-barHeight; g_.setColor(Color.black); // outline bar g_.drawRect(barOrg.x, barOrg.y, barWidth-sep, barHeight); g_.setColor(Color.red); // fill bar g_.fillRect(barOrg.x+1, barOrg.y+1, barWidth-sep-1, barHeight-1); barOrg.x += barWidth + sep; // space between } g_.setColor(c); //reset color } public void paintBackground(Graphics g_, Color c_){ Color c=g_.getColor(); g_.setColor(c_); g_.fillRect(0, 0, _rect.width, _rect.height); g_.setColor(c); } } // end class BarChart // debugging code no longer needed /* debugPrintln("_rect.x/y/w/h=" + _rect.x + " "+ _rect.y + " "+ _rect.width + " "+ _rect.height); public void debugPrintln(String s_){ if(_debug>0) System.out.println(s_); } debugPrintln("paintBars: barWidth=" + barWidth + ", _rect.height=" + _rect.height + ", _rect.width=" + _rect.width); debugPrintln(" scaleFactor=" + scaleFactor + ", _set.length()=" + _set.length() + ",_set.max()=" + _set.max() ); */