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:00

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

查看更多
Ridiculous、
3楼-- · 2020-03-12 04:01

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.

查看更多
我想做一个坏孩纸
4楼-- · 2020-03-12 04:08

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

查看更多
▲ chillily
5楼-- · 2020-03-12 04:15

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

查看更多
该账号已被封号
6楼-- · 2020-03-12 04:16

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

查看更多
冷血范
7楼-- · 2020-03-12 04:17

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.

查看更多
登录 后发表回答