Color name to string java

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

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.

8 Answers 8

You may wish to use getRGB() instead of toString() . You can call

String colorS = Integer.toString(myColor.getRGB());

Color c = new Color(Integer.parseInt(colorS));

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

What if the Color is defined in another ColorSpace? r/g/b would likely be an approximation after all.

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.

Источник

Android get color as string value

You can use the deprecated getColor() no problem. Just delete the «getColor(. )» and type it out again, use intellisense to complete the method call with the Android deprecated getColor call and you’re good.

All of the solutions here using Integer.toHexString() break if you would have leading zeroes in your hex string. Colors like #0affff would result in #affff . Use this instead:

String.format("#%06x", ContextCompat.getColor(this, R.color.your_color) & 0xffffff) 
String.format("#%08x", ContextCompat.getColor(this, R.color.your_color) & 0xffffffff) 

The answers provided above are not updated.

String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.dark_sky_blue) & 0x00ffffff); 

Cause getResources().getColor need api > 23. So this is better: Just for the sake of easy copy & paste:

Integer.toHexString( ContextCompat.getColor( getContext(), R.color.someColor ) );

Or if you want it without the transparency:`

Integer.toHexString( ContextCompat.getColor( getContext(), R.color.someColor ) & 0x00ffffff );

For API above 21 you can use

getString(R.color.color_name); 

This will return the color in a string format. To convert that to a color in integer format (sometimes only integers are accepted) then:

Color.parseColor(getString(R.color.color_name)); 

The above expression returns the integer equivalent of the color defined in color.xml file

Источник

How To Print String representation of Color in Java

I have an array of colours of size n. In my program, the number of teams is always

private static Color[] TEAM_COLORS = ; 

When I print information about the players in the console, I want to print what color is associated with them. When I print the color, I get

I understand that this is how Java prints colours. I was wondering if there was a way to instead print BLUE, RED, etc. (so the pre-defined color string).

Those static fields you’re using from the Color class are there for convenience and reference Color objects which do not have any sort of textual names; they are RGB values.

I take that back, looking more closely at the post makes me realize the OP was talking about the pre-defined colors, and a limited number of them.

@AndrewThompson — Yeah but it doesn’t change anything, there’s no matching String s for them in the Color class. You have to do the mapping yourself.

7 Answers 7

Extending @Jon_Skeet reply by adding name also to the enum.

public enum NamedColor < BLUE(Color.BLUE, "Blue"), RED(Color.RED, "Red"), . ; private final Color awtColor; private final String colorName; private NamedColor(Color awtColor, String name) < this.awtColor = awtColor; this.colorName = name; >public Color getAwtColor() < return awtColor; >public String getColorName() < return colorName; >> 

NOTE: IF voting this pls vote @Jon_Skeet reply too as it is extension of that.

One option would be to create a NamedColor enum:

public enum NamedColor < BLUE(Color.BLUE), RED(Color.RED), . ; private final Color awtColor; private NamedColor(Color awtColor) < this.awtColor = awtColor; >public Color getAwtColor() < return awtColor; >> 

You’d then make your TEAM_COLORS array an array of NamedColor values instead of Color values, and fetch the AWT color when you need it. The default toString implementation of an enum is its name.

Another alternative would be to create your own Map and consult that when you need the string representation for a color.

@Jon_Skeet I just extend your reply a bit by adding colorName also as an attribute to the enum. that way everything is in one place.

@havexz: You could do that — but I’d normally just use the enum name unless I had any good reason not to.

@JonSkeet I totally agree with you. Extended code works in situations where all string literals are not external to code (specifically not worried about multi-linugal). But if we have string literals coming from outside code (based on the language) we can than remove the colorName member variable and use the api only which fetches from external source via some helper class. But true all these soln has to be thought of according to situation before choosing.

Источник

Getting a string representing the color name from an instance of Color

and I want to get the string «Black» . I know this should be possible using Java reflection, but I’m not very familiar with it. Thank you.

2 Answers 2

Color class has only few non-static fields which are

name | type ----------+--------------- value | int frgbvalue | float[] fvalue | float[] falpha | float cs | java.awt.color.ColorSpace 

and none of this fields store color name. Also it doesn’t have any method which would check if color you are using is equal to one of its predefined ones and stored in static references like

public final static Color black = new Color(0, 0, 0); public final static Color BLACK = black; 

But nothing stops you from implementing your own method which will do it for you. Such method can look like

public static Optional colorName(Color c) < for (Field f : Color.class.getDeclaredFields()) < //we want to test only fields of type Color if (f.getType().equals(Color.class)) try < if (f.get(null).equals(c)) return Optional.of(f.getName().toLowerCase()); >catch (IllegalArgumentException | IllegalAccessException e) < // shouldn't not be thrown, but just in case print its stacktrace e.printStackTrace(); >> return Optional.empty(); > 
System.out.println(colorName(Color.BLACK).orElse("no name found")); System.out.println(colorName(new Color(10, 20, 30)).orElse("no name found")); System.out.println(colorName(null).orElse("no name found")); 
black no name found no name found 

Источник

Возможно ли преобразовать Color в String?

Как создать массив со строками — string, string, Color Clr = Color.Black?
Как создать массив со строками — string, string, Color Clr = Color.Black? Имеется массив.

Нельзя преобразовать тип Tuple к string
Здравствуйте, у меня возникла проблема. При запуске кода, вылезает ошибка "Нельзя преобразовать тип.

Из String в Color.
Доброго времени суток! Имеется переменная типа string TheColor = "ff4f00"; Требуется форме задать.

farshmaker, а собственно как бы назывался цвет вроде [17, 63, 119]? Вот JVM тоже неизвестно что это за цвет.

то какой ты результат хочешь? Красный и чуть чуть зеленого?)
Я думаю, что это не возможно.
А насчет этого кода, думаю правильнее будет так, хотя у меня и это не компилируется:

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

ЦитатаСообщение от Борланд Посмотреть сообщение

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

Ну для популярных цветом можно было бы составить преобразование. Ведь когда люди задают цвет фигуре, наверное, чаще всего пишут вроде:

g.setColor(new Color(156, 94, 212))

И тогда обратно можно было бы получить стринговый эквивалент. В c# же toString() возвращает имена популярных цветов.

Ну нет, так нет. Сделал пока так: с помощью метода getRGB() получил некие int значения(отрицательные) для 4х цветов и в switch-case присваиваю соответствующие имена String переменной. Для лабы хватит)

то какой ты результат хочешь? Красный и чуть чуть зеленого?)

Эксперт PythonЭксперт JavaЭксперт CЭксперт С++

Лучший ответ

Сообщение было отмечено farshmaker как решение

Решение

EagleAlex, абстрактные величины вроде «много красного, в меру зелёного, совесем нет синего» это значение сильно сокращают
farshmaker, не задаваясь вопросом, зачем оно нужно

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import java.awt.Color; public class GuessColor { public static void main(String[] args) { Color[] colors = { new Color(255, 0, 0), new Color(0, 255, 0), new Color(0, 0, 255) }; for ( Color c : colors ) { String name = "Unknown"; if ( Color.RED.equals(c) ) name = "Red"; else if ( Color.GREEN.equals(c) ) name = "Green"; /* ещё 100500 вариантов */ else if ( Color.BLUE.equals(c) ) name = "Blue"; System.out.println(name); } } }

Источник

Читайте также:  Title for javascript alert
Оцените статью