I have a question regarding the awt Color class in Java.
I am currently using the class abbreviations such as Color.RED and Color.BLACK. I also have a list of three integers such as the following:
int var1 = 0
int var2 = 0
int var3 = 255
Is there a method to convert these integers into the appropriate Java Color name?
There is no way to do this with a single method in the Java core classes. However, you can fairly easily do this yourself in two ways.
First, create a HashMap of Colors that contains all the colors you want:
HashMap<Color, String> colors = new HashMap<Color, String>();
colors.put(Color.BLACK, "BLACK");
colors.put(Color.BLUE, "BLUE");
colors.put(Color.CYAN, "CYAN");
colors.put(Color.DARK_GRAY, "DARK_GRAY");
colors.put(Color.GRAY, "GRAY");
colors.put(Color.GREEN, "GREEN");
colors.put(Color.LIGHT_GRAY, "LIGHT_GRAY");
colors.put(Color.MAGENTA, "MAGENTA");
colors.put(Color.ORANGE, "ORANGE");
colors.put(Color.PINK, "PINK");
colors.put(Color.RED, "RED");
colors.put(Color.WHITE, "WHITE");
colors.put(new Color(192, 0, 255), "PURPLE");
colors.put(new Color(0xBADA55), "BADASS_GREEN");
colors.put(new Color(0, 0, 128), "DARK_BLUE");
Then, create a new Color out of the RGB values you have:
Color color = new Color(var1, var2, var3);
Last, get the value in colors for the key color:
String colorName = colors.get(color);
This is potentially a less brittle way, but does have issues, and doesn't work as-is. You'll need to catch some exceptions, and maybe handle the case where a field isn't static and you can't just do f.get(null).
Create a new Color out of the RGB values you have:
Color color = new Color(var1, var2, var3);
Then
Class object from the Color class with getClass().getDeclaredFields().Arrays.stream()filter(), so it only contains all the enum constants that equal the color you made (there should be either one or zero).toArray() to turn the stream into an array.[0]. This will throw an ArrayIndexOutOfBoundsException if there isn't a predefined color matching your color.Enum's toString().String colorName = Arrays.stream(Color.getClass().getDeclaredFields())
.filter(f -> f.get(null).equals(color))
.toArray()[0]
.toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With