01: /*
02: * Copyright 2006 Ethan Nicholas. All rights reserved.
03: * Use is subject to license terms.
04: */
05: package jaxx.types;
06:
07: import java.awt.*;
08: import java.lang.reflect.*;
09:
10: public class ColorConverter implements TypeConverter {
11: public String getJavaCode(Object object) {
12: Color color = (Color) object;
13: return "new Color(" + color.getRed() + ", " + color.getGreen()
14: + ", " + color.getBlue() + ")";
15: }
16:
17: public Object convertFromString(String string, Class type) {
18: if (type != Color.class)
19: throw new IllegalArgumentException("unsupported type: "
20: + type);
21: if (string.length() == 7 && string.charAt(0) == '#') {
22: return new Color(Integer.parseInt(string.substring(1), 16));
23: } else {
24: try {
25: Field color = Color.class.getField(string);
26: return color.get(null);
27: } catch (NoSuchFieldException e) {
28: throw new IllegalArgumentException(
29: "colors must be of the form #xxxxxx ('#' followed by six hexadecimal digits), or the name of a constant field in java.awt.Color (found: '"
30: + string + "')");
31: } catch (IllegalAccessException e) {
32: throw new RuntimeException(e);
33: }
34: }
35: }
36: }
|