View Javadoc

1   package net.sf.statcvs.charts;
2   
3   import java.awt.Color;
4   
5   /**
6    * Utility class for chart related stuff.
7    * 
8    * @author Richard Cyganiak
9    * @version $Id: ChartUtils.java,v 1.3 2008/04/02 11:22:15 benoitx Exp $
10   */
11  public class ChartUtils {
12      private static final String MAGIC_SEED_1 = "0 Ax-!";
13      private static final String MAGIC_SEED_2 = "!Z x5";
14  
15      private ChartUtils() {
16          // Only static methods
17      }
18  
19      /**
20       * Returns a distinct <code>Color</code> for a <code>String</code> argument.
21       * The algorithm tries to provide different colors for similar strings, and
22       * will return equal colors for equal strings. The colors will all have
23       * similar brightness and maximum intensity. Useful for chart coloring.
24       * @param s a <code>String</code> to get a color for
25       * @return a distinct <code>Color</code> for a <code>String</code> argument.
26       * The algorithm tries to provide different colors for similar strings, and
27       * will return equal colors for equal strings. The colors will all have
28       * similar brightness and maximum intensity. Useful for chart coloring.
29       */
30      public static Color getStringColor(final String s) {
31          double d = (MAGIC_SEED_1 + s + MAGIC_SEED_2).hashCode();
32          d -= Integer.MIN_VALUE;
33          d /= ((double) Integer.MAX_VALUE - (double) Integer.MIN_VALUE);
34          d *= 3;
35          // Now 0 <= d < 3
36          if (d < 1) {
37              final int r = (int) ((1 - d) * MAX_RED);
38              final int g = (int) (d * MAX_GREEN);
39              return new Color(r, g, 0);
40          } else if (d < 2) {
41              final int g = (int) ((2 - d) * MAX_GREEN);
42              final int b = (int) ((d - 1) * MAX_BLUE);
43              return new Color(0, g, b);
44          } else {
45              final int r = (int) ((d - 2) * MAX_RED);
46              final int b = (int) ((3 - d) * MAX_BLUE);
47              return new Color(r, 0, b);
48          }
49      }
50  
51      // Use values less than 256 here, or the colors will get too bright
52      private static double MAX_RED = 200;
53      private static double MAX_GREEN = 150;
54      private static double MAX_BLUE = 250;
55  }