1 package org.opentrafficsim.xml.bindings;
2
3 import java.awt.Color;
4
5 import javax.xml.bind.annotation.adapters.XmlAdapter;
6
7 import org.djutils.logger.CategoryLogger;
8
9
10
11
12
13
14
15
16
17
18
19 public class ColorAdapter extends XmlAdapter<String, Color>
20 {
21
22 @Override
23 public Color unmarshal(final String field) throws IllegalArgumentException
24 {
25 try
26 {
27 String colorStr = field.replaceAll("\\s", "");
28
29 if (colorStr.startsWith("#"))
30 return Color.decode(colorStr);
31
32 if (colorStr.startsWith("RGB"))
33 {
34 String c = colorStr.substring(3).replace("(", "").replace(")", "");
35 String[] rgb = c.split(",");
36 int r = Integer.parseInt(rgb[0].trim());
37 int g = Integer.parseInt(rgb[1].trim());
38 int b = Integer.parseInt(rgb[2].trim());
39 return new Color(r, g, b);
40 }
41
42 if (colorStr.equals("BLACK"))
43 return Color.BLACK;
44 if (colorStr.equals("BLUE"))
45 return Color.BLUE;
46 if (colorStr.equals("CYAN"))
47 return Color.CYAN;
48 if (colorStr.equals("DARK_GRAY"))
49 return Color.DARK_GRAY;
50 if (colorStr.equals("GRAY"))
51 return Color.GRAY;
52 if (colorStr.equals("GREEN"))
53 return Color.GREEN;
54 if (colorStr.equals("LIGHT_GRAY"))
55 return Color.LIGHT_GRAY;
56 if (colorStr.equals("MAGENTA"))
57 return Color.MAGENTA;
58 if (colorStr.equals("ORANGE"))
59 return Color.ORANGE;
60 if (colorStr.equals("PINK"))
61 return Color.PINK;
62 if (colorStr.equals("RED"))
63 return Color.RED;
64 if (colorStr.equals("WHITE"))
65 return Color.WHITE;
66 if (colorStr.equals("YELLOW"))
67 return Color.YELLOW;
68 }
69 catch (Exception exception)
70 {
71 CategoryLogger.always().error(exception, "Problem parsing color '" + field + "'");
72 throw new IllegalArgumentException("Error parsing color " + field, exception);
73 }
74 CategoryLogger.always().error("Problem parsing color '" + field + "'");
75 throw new IllegalArgumentException("Error parsing color " + field);
76 }
77
78
79 @Override
80 public String marshal(final Color color) throws IllegalArgumentException
81 {
82 return "RGB(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue() + ")";
83 }
84
85 }