tags:

views:

365

answers:

7

Hi,

In order to save Color attributes of a graphical object in my application, I saved the string representation of this Color in a data file. For instance, for red I save: java.awt.Color[r=255,g=0,b=0]. How can I convert this string representation into a Color so that I can use it again after loading my data file ?

Thank you.

+3  A: 

From the documentation of Color#toString

Returns a string representation of this Color. This method is intended to be used only for debugging purposes. The content and format of the returned string might vary between implementations. The returned string might be empty but cannot be null.

In other words, I wouldn't rely on being able to back-convert the string to the Color. If you insist on doing this, however, you can try to parse the numbers out of the string and hope that it will work with no guarantees.

Something like this seems to work for ME for NOW:

    Scanner sc = new Scanner("java.awt.Color[r=1,g=2,b=3]");
    sc.useDelimiter("\\D+");
    Color color = new Color(sc.nextInt(), sc.nextInt(), sc.nextInt());

I don't recommend actually doing this, however.

polygenelubricants
+7  A: 

Using toString() "might vary between implementations." Instead save String.valueOf(color.getRGB()) for later reconstruction.

trashgod
+2  A: 

The easiest thing is to rethink the way you store the string representation. Get rid of all the labeling, and just store red as the string "0xFF0000". Then you can easily parse that string to get the single value for rgb, and send it to the Color constructor.

The alternative is to parse the more complicated string as you are now saving it "java.awt.Color[r=255,g=0,b=0]".

You can see the constructors for Color here: http://java.sun.com/javase/6/docs/api/ (search "all classes" for Color).

Peter

Peter vdL
+2  A: 

I suggest you look into java's built-in serialisation technology instead. (I note that Color implements Serializable.)

crazyscot
+3  A: 

You may wish to use getRGB() instead of toString(). You can call

String colorS = Integer.toString(myColor.getRGB());

Then you can call

Color c = new Color(integer.parseInt(colorS));

iter
+2  A: 

Use the getRGB() method to get the int representation of the Color, then you save the int value and recreate the Color using that value. No parsing needed.

camickr
+2  A: 

Don't use the toString(). Use getRGB() / new Color(rgb) to save/restore the value of the color.

Bozho