import java.awt.*;

public class BarGraph extends Canvas {

  private int xmin, xmax, ymin, ymax;
  private Color bgcolor,barcolor;
  private int[] table;

  public BarGraph () {} // default constructor

  public BarGraph (int xminIn, int xmaxIn, int yminIn, int ymaxIn,
                   Color bgcolorIn, Color barcolorIn) {
    set (xminIn, xmaxIn, yminIn, ymaxIn, bgcolorIn, barcolorIn);
  }

  public void set (int xminIn, int xmaxIn, int yminIn, int ymaxIn,
                   Color bgcolorIn, Color barcolorIn) {
    xmin = xminIn;
    xmax = xmaxIn;
    ymin = yminIn;
    ymax = ymaxIn;
    bgcolor = bgcolorIn;
    barcolor = barcolorIn;
    table = new int[xmax-xmin+1];
    for (int i=0; i<=xmax-xmin; ++i)
      table[i] = Integer.MIN_VALUE;
  }

  public void clear() {
    for (int i=0; i<=xmax-xmin; ++i)
      table[i] = Integer.MIN_VALUE;
  }

  public void plot (int x, int y) {
    table[x-xmin] = y;
    repaint();
  }

  public void update(Graphics g) {
    Dimension d = getSize();
    g.setColor(bgcolor);
    g.fillRect(0,0,d.width,d.height);
    if (xmax==xmin) return;  // parameters not yet initialized
    g.setColor(barcolor);
    for (int i=0; i<table.length; ++i)
      if (table[i] > ymin) {
        int x = i * d.width / (xmax-xmin+1);
	int nextx = (i+1) * d.width / (xmax-xmin+1);
	int width = nextx - x - 1;
	if (width < 1)
	  width = 1;
        int height = d.height * (table[i]-ymin) / (ymax-ymin);
        g.fillRect(x,d.height-height,width,height);
      }
  }

  public void paint(Graphics g) {
    update(g);
  }
}

