/Users/lyon/j4p/src/graphics/ColorGridCanvas.java

1    package graphics; 
2     
3     
4    public class ColorGridCanvas extends java.awt.Canvas { 
5        int rows, cols; 
6        java.awt.Color colors[]; 
7     
8        ColorGridCanvas(int numColors) { 
9            setSize(400, 400); 
10           bookExamples.ch27BusinessGraphics.charts.ColorUtils cu = 
11                   new bookExamples.ch27BusinessGraphics.charts.ColorUtils(numColors); 
12           colors = cu.getColorMap(); 
13           cols = Math.min(16, numColors); 
14           rows = (numColors - 1) / cols + 1; 
15       } 
16    
17       // Returns the color value at (x, y). 
18       java.awt.Color getColor(int x, int y) { 
19           java.awt.Dimension d = getSize(); 
20           int cellW = d.width / cols; 
21           int cellH = d.height / rows; 
22    
23           x /= cellW; 
24           y /= cellH; 
25    
26           // Return the last color if out of bounds. 
27           return colors[Math.min(colors.length - 1, y * cols + x)]; 
28       } 
29    
30       public void paint(java.awt.Graphics g) { 
31           java.awt.Dimension d = getSize(); 
32           int cellW = d.width / cols; 
33           int cellH = d.height / rows; 
34    
35           for (int i = 0; i < colors.length; i++) { 
36               int r = i / cols; 
37               int c = i % cols; 
38    
39               g.setColor(colors[i]); 
40               g.fillRect(c * cellW, r * cellH, cellW, cellH); 
41           } 
42       } 
43    
44       public static void main(String args[]) { 
45           gui.ClosableJFrame cf = new gui.ClosableJFrame(); 
46           java.awt.Container c = cf.getContentPane(); 
47           c.add(new ColorGridCanvas(1024*2)); 
48           c.setLayout(new java.awt.FlowLayout()); 
49           cf.setSize(400, 400); 
50           cf.setVisible(true); 
51       } 
52   }