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