import java.awt.*; import java.applet.*; 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; } public void drawHistogram(String dataString) { drawHistogram(dataString.split("\\s+")); } public void drawHistogram(String[] data) { if (data.length > 1) { offScreenImage = createImage(WIDTH, HEIGHT); offScreenGraphics = offScreenImage.getGraphics(); int maxValue = 0; for (int i = 0; i < data.length; i+=2) { int nextValue = Integer.parseInt(data[i+1]); if (nextValue > maxValue) { maxValue = nextValue; } } int barHeight = (int)(2.0*HEIGHT/data.length); double widthFactor = (double)WIDTH/maxValue; for (int i = 0; i < data.length; i+=2) { int barWidth = (int)(Integer.parseInt(data[i+1]) * widthFactor); 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[i]+" ("+data[i+1]+")", 4, (i+1)*barHeight/2); } paint(getGraphics()); } } public void paint(Graphics g) { g.drawImage(offScreenImage, 0, 0, null); } }