1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.jelly.tags.swing.converters;
17
18 import java.awt.Color;
19 import java.awt.SystemColor;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.Modifier;
22
23 import org.apache.commons.beanutils.Converter;
24
25 /***
26 * A Converter that turns Strings in the form "#uuuuuu" (as RGB triple)
27 * or the name of one of the {@link Color}-constants of the class
28 * {@link Color} or {@link SystemColor}.
29 * <p>
30 * TODO: provide support of ARGB colors as well.<br>
31 * Future: provide support for color-spaces, indexed colors...
32 * (in particular theme-based colors)
33 *
34 * @author <a href="mailto:paul@activemath.org">Paul Libbrecht</a>
35 * @version $Revision: 155420 $
36 */
37 public class ColorConverter implements Converter {
38
39 private static String usageText =
40 "A color is encoded as a java.awt.Color name or a #xxxxxx triple of hex-bytes.";
41
42 public Object convert(Class type, Object value) {
43 if (value != null) {
44 String s = value.toString();
45 if (s.length() <= 1) {
46 throw new IllegalArgumentException(usageText);
47 }
48 if (s.charAt(0) == '#') {
49 if (s.length() != 7) {
50 throw new IllegalArgumentException(usageText);
51 }
52 int colorValue = 0;
53 try {
54 colorValue = Integer.parseInt(s.substring(1), 16);
55 return new Color(colorValue);
56 }
57 catch (NumberFormatException ex) {
58 throw new IllegalArgumentException(
59 "Can't parse \""
60 + s
61 + "\" as an hexadecimal number: "
62 + ex);
63 }
64 }
65 else {
66
67 try {
68
69 Field f = SystemColor.class.getField(s);
70 if (f == null
71 || !Modifier.isStatic(f.getModifiers())
72 || !Modifier.isFinal(f.getModifiers())
73 || !Modifier.isPublic(f.getModifiers())
74 || !Color.class.isAssignableFrom(f.getType())) {
75
76 throw new IllegalArgumentException(usageText);
77 }
78 return (Color) f.get(SystemColor.class);
79 }
80 catch (Exception ex) {
81 throw new IllegalArgumentException(
82 "Can't parse \"" + s + "\" as a color-name: " + ex);
83 }
84 }
85 }
86 return null;
87 }
88
89 }