Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to convert a Color.toString() into a Color?

Tags:

java

colors

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.

like image 990
Amokrane Chentir Avatar asked Mar 06 '10 22:03

Amokrane Chentir


People also ask

How do you change a string to a color in Java?

In . NET you can achieve something like this: Color yellowColor = Color. FromName("yellow");

How do you change the color of something in Java?

Paint - Double click on any color at the bottom of the screen. - Choose "Define Custom Colors". - Select a color and/or use the arrows to achieve the desired color. are the numbers needed to create your new Java color.

What Colour is Java?

It's a dark brown. 3 of 3 found this helpful.


2 Answers

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));

like image 65
iter Avatar answered Oct 04 '22 20:10

iter


Stephan's answer helped me with this. However, I found that I needed to add a 'true' to the syntax in order to restore the color.

// convert to string
String colorS = Integer.toString(myColor.getRGB());

// restore colour from string
Color c = new Color(Integer.parseInt(colorS), true);
like image 36
Christian Avatar answered Oct 04 '22 20:10

Christian