// Histogram class // Dave Reed // 11/10/01 ////////////////////////////////////////// import java.awt.*; import java.applet.*; import java.util.Vector; public class Histogram extends Applet { private int WIDTH, HEIGHT; private Image offScreenImage; private Graphics offScreenGraphics; public void init() { Dimension dim = getSize(); WIDTH = dim.width; HEIGHT = dim.height; } private Vector Vectorize(String str) { Vector items = new Vector(); while (str.length() > 0) { int index = 0; while (index < str.length() && Character.isWhitespace(str.charAt(index))) { index++; } if (index < str.length()) { String item = ""; while (index < str.length() && !Character.isWhitespace(str.charAt(index))) { item += str.charAt(index); index++; } items.addElement(item); } if (index < str.length()) { str = str.substring(index+1, str.length()); } else { str = ""; } } return items; } public void drawHistogram(String dataString) { Vector data = Vectorize(dataString); if (data.size() > 1) { offScreenImage = createImage(WIDTH, HEIGHT); offScreenGraphics = offScreenImage.getGraphics(); int max = Integer.parseInt((String)data.elementAt(1)); for (int i = 3; i < data.size(); i+=2) { if (Integer.parseInt((String)data.elementAt(i)) > max) { max = Integer.parseInt((String)data.elementAt(i)); } } int barHeight = (int)(2.0*HEIGHT/data.size()); for (int i = 0; i < data.size(); i+=2) { int value = Integer.parseInt((String)data.elementAt(i+1)); int barWidth = (WIDTH*value)/max; offScreenGraphics.setColor(Color.yellow); offScreenGraphics.fillRect(0, barHeight*i/2, barWidth, barHeight); offScreenGraphics.setColor(Color.black); offScreenGraphics.drawRect(0, barHeight*i/2, barWidth, barHeight); offScreenGraphics.drawString(data.elementAt(i)+ " ("+ value +")", 5, (i+1)*barHeight/2); } paint(getGraphics()); } } public void paint(Graphics g) { g.drawImage(offScreenImage, 0, 0, null); } }