]> gitweb.fperrin.net Git - GpsPrune.git/blob - src/tim/prune/config/ColourUtils.java
a3c11880dfe69b53857b536345eb5cbf44c72f88
[GpsPrune.git] / src / tim / prune / config / ColourUtils.java
1 package tim.prune.config;
2
3 import java.awt.Color;
4
5 /**
6  * Class to hold static methods for handling colours
7  * including converting to and from hex code Strings
8  */
9 public abstract class ColourUtils
10 {
11         /**
12          * Convert a string into a Color object
13          * @param inValue 6-character hex code
14          * @return corresponding colour
15          */
16         public static Color colourFromHex(String inValue)
17         {
18                 Color retVal = null;
19                 if (inValue != null && inValue.length() == 6)
20                 {
21                         try
22                         {
23                                 final int redness = convertToInt(inValue.substring(0, 2));
24                                 final int greenness = convertToInt(inValue.substring(2, 4));
25                                 final int blueness = convertToInt(inValue.substring(4, 6));
26                                 retVal = new Color(redness, greenness, blueness);
27                         }
28                         catch (NumberFormatException nfe) {} // colour stays null
29                 }
30                 return retVal;
31         }
32
33         /**
34          * @param inPair two-digit String representing hex code
35          * @return corresponding integer (0 to 255)
36          */
37         private static int convertToInt(String inPair)
38         {
39                 int val = Integer.parseInt(inPair, 16);
40                 if (val < 0) val = 0;
41                 return val;
42         }
43
44         /**
45          * Make a hex code string for the given colour
46          * @param inColour colour
47          * @return 6-character hex code
48          */
49         public static String makeHexCode(Color inColour)
50         {
51                 return convertToHex(inColour.getRed()) + convertToHex(inColour.getGreen()) + convertToHex(inColour.getBlue());
52         }
53
54         /**
55          * @param inValue integer value from 0 to 255
56          * @return two-character hex code
57          */
58         private static String convertToHex(int inValue)
59         {
60                 // Uses lower case a-f
61                 String code = Integer.toHexString(inValue);
62                 // Pad with leading 0 if necessary
63                 return (inValue < 16 ? "0" + code : code);
64         }
65 }