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