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.
Don't use the
toString()
. UsegetRGB()
/new Color(rgb)
to save/restore the value of the color.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.
Using
toString()
"might vary between implementations." Instead saveString.valueOf(color.getRGB())
for later reconstruction.I suggest you look into java's built-in serialisation technology instead. (I note that Color implements Serializable.)
You may wish to use
getRGB()
instead oftoString()
. You can callString colorS = Integer.toString(myColor.getRGB());
Then you can call
Color c = new Color(Integer.parseInt(colorS));
From the documentation of
Color#toString
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:
I don't recommend actually doing this, however.