01: /*
02: * @(#) HexColorConverter.java
03: *
04: * Copyright 2002 - 2003 JIDE Software. All rights reserved.
05: */
06: package com.jidesoft.converter;
07:
08: import java.awt.*;
09:
10: /**
11: * Converts Color to/from #xxxxxx format. For example #000000 is Color(0, 0, 0)
12: * and #FF00FF is Color(255, 0, 255).
13: */
14: public class HexColorConverter extends ColorConverter {
15: /**
16: * Creates a HexColorConverter.
17: */
18: public HexColorConverter() {
19: }
20:
21: protected String getHexString(int color) {
22: String value = Integer.toHexString(color).toUpperCase();
23: if (value.length() == 1) {
24: value = "0" + value;
25: }
26: return value;
27: }
28:
29: public String toString(Object object, ConverterContext context) {
30: if (object instanceof Color) {
31: Color color = (Color) object;
32: StringBuffer colorText = new StringBuffer("#");
33: colorText.append(getHexString(color.getRed()));
34: colorText.append(getHexString(color.getGreen()));
35: colorText.append(getHexString(color.getBlue()));
36: return new String(colorText);
37: } else {
38: return "";
39: }
40: }
41:
42: public boolean supportToString(Object object,
43: ConverterContext context) {
44: return true;
45: }
46:
47: public boolean supportFromString(String string,
48: ConverterContext context) {
49: return true;
50: }
51:
52: public Object fromString(String string, ConverterContext context) {
53: if (string == null || string.trim().length() == 0) {
54: return null;
55: }
56: if (string.startsWith("#")) {
57: string = string.substring(1);
58: }
59: if (string.length() > 6) {
60: string = string.substring(string.length() - 6);
61: }
62: int value = 0;
63: try {
64: value = Integer.parseInt(string, 16);
65: } catch (NumberFormatException e) {
66: return null;
67: }
68: return new Color(value);
69: }
70: }
|