package graphics;


public class ColorGrid extends java.awt.Canvas {
  int rows, cols;
  java.awt.Color colors[];

  ColorGrid(int numColors) {
    setSize(200, 200);
    graphics.charts.ColorUtils cu =
        new graphics.charts.ColorUtils(numColors);
    colors = cu.getColorMap();
    cols = Math.min(16, numColors);
    rows = (numColors - 1) / cols + 1;
  }

  // Returns the color value at (x, y).
  java.awt.Color getColor(int x, int y) {
    java.awt.Dimension d = getSize();
    int cellW = d.width / cols;
    int cellH = d.height / rows;

    x /= cellW;
    y /= cellH;

    // Return the last color if out of bounds.
    return colors[Math.min(colors.length - 1, y * cols + x)];
  }

  public void paint(java.awt.Graphics g) {
    java.awt.Dimension d = getSize();
    int cellW = d.width / cols;
    int cellH = d.height / rows;

    for (int i = 0; i < colors.length; i++) {
      int r = i / cols;
      int c = i % cols;

      g.setColor(colors[i]);
      g.fillRect(c * cellW, r * cellH, cellW, cellH);
    }
  }

  public static void main(String args[]) {
    gui.ClosableJFrame cf = new gui.ClosableJFrame();
    java.awt.Container c = cf.getContentPane();
    c.add(new ColorGrid(64));
    c.setLayout(new java.awt.FlowLayout());
    cf.setSize(200, 200);
    cf.setVisible(true);
  }
}