Umesh Kacha
Umesh Kacha

Reputation: 13686

java.awt.color to java.lang.string conversion

I would like to convert java.awt.color object to string.

Color c = new Color(255,0,0);
System.out.print(Color.toString);

It prints java.awt.Color[r=255,g=0,b=0]

Now I suppose to parse this string and decode the color name e.g blue etc.

I was thinking is there any other way I can directly convert this Color into String.

Thanks in advance.

EDIT: I would like to store this color values in database. Should I store it as a String or RGB value?

Upvotes: 2

Views: 5017

Answers (4)

trashgod
trashgod

Reputation: 205875

You'd have to start with a list of agreed-upon color names, such as these. Then build a Map<Color, String>) from which to get the name.

Upvotes: 1

Bozho
Bozho

Reputation: 597412

No. At least because:

  • few rgb combinations have a color name
  • java does not hold the color names in all languages it has locale support for

But you can do otherwise. Get the predefined constants in Color and check if any of them has the same RGB as the given color. If so - print the name.

As for your added question - store it as RGB value rather than string.

Upvotes: 6

Mathias Schwarz
Mathias Schwarz

Reputation: 7197

You could use the HTML4 basic and extends color keywords. They should be possible to get directly from the rgb values using a table like this: http://www.w3.org/TR/css3-color/#html4

Upvotes: 0

Peter O.
Peter O.

Reputation: 32908

You can use the methods getRed(), getBlue(), getGreen(), and getAlpha() to get the color's components instead of parsing the string returned from toString(). You can also compare the color with the static fields in java.awt.Color (using Equals.)

Upvotes: 0

Related Questions