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

2020-03-12 03:29发布

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.

标签: java colors
8条回答
我命由我不由天
2楼-- · 2020-03-12 04:18

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);
查看更多
男人必须洒脱
3楼-- · 2020-03-12 04:19

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

查看更多
登录 后发表回答