/Users/lyon/j4p/src/bookExamples/ch27BusinessGraphics/charts/ColorUtils.java

1    package bookExamples.ch27BusinessGraphics.charts; 
2     
3    import java.awt.*; 
4     
5    /** 
6     * ColorUtils generates 
7     * bright colors for each slice of the pie. 
8     * Requires an integer indicating how many slices there are altogether 
9     * to be constructed.<BR> 
10    * Global variables: 
11    * <UL> 
12    * <LI> ColorMap: An array of colors, initialized to null 
13    * </UL> 
14    * 
15    * @author  Allison McHenry 
16    * @author  Douglas Lyon, PhD 
17    * @since   JDK 1.3 
18    */ 
19    
20    
21   public class ColorUtils { 
22    
23       private Color colorMap [] = null; 
24    
25       /** 
26        *  Constructor containing number of slices of pie that need to be drawn. 
27        *  Calls getColorMap function which gets each color. 
28        *  @param nc   Total number of colors needed (xVals.length) 
29        *  @see        #getColorMap 
30        */ 
31       public ColorUtils(int nc) { 
32           initColorMap(nc); 
33       } 
34    
35       /** 
36        *  Creates the Color Map using the HSB (hue, saturation, brightness) 
37        *  color scale, guaranteeing that each color will be fully satuated (1), 
38        *  fully bright(1) and of a random hue(h). 
39        *  Colors are more differentiated if there are few of them. 
40        * 
41        *  @param n    Number of colors needed, from constructor 
42        *  @return c   An array of colors to be used in drawing the pie 
43        *  @see        java.awt.Color.#HSBtoRGB 
44        */ 
45       private void initColorMap(int n) { 
46           Color c [] = new Color[n]; 
47           int i = 0; 
48           for (float h = 0; i < c.length; h = (float) (h + 1.0 / n)) { 
49               c[i] = new Color(Color.HSBtoRGB(h, 1, 1)); 
50               i++; 
51           } 
52           colorMap = c; 
53       } 
54    
55       public Color[] getColorMap() { 
56           return colorMap; 
57       } 
58    
59    
60       /** 
61        *  Walks through the 
62        *  array of colors and matches the data at index i with the color in 
63        *  the color map at index i. 
64        * 
65        *  @param i    Which specific slice is being drawn right now 
66        *  @return c   One color from the color map to be used in drawing this slice 
67        *  @see        PieGraph.#drawGraph 
68        */ 
69       public Color getColor(int i) { 
70           return colorMap[i % colorMap.length]; 
71       } 
72    
73   }