Java中的颜色类 [英] Color Class in Java
问题描述
我对Java中的awt Color
类有疑问.
I have a question regarding the awt Color
class in Java.
我目前正在使用类缩写,例如Color.RED
和Color.BLACK
.我还列出了三个整数,例如:
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
是否存在将这些整数转换为适当的Java Color
名称的方法?
Is there a method to convert these integers into the appropriate Java Color
name?
推荐答案
在Java核心类中,没有办法使用单个方法来完成此操作.但是,您可以通过两种方式轻松地自己完成此操作.
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.
从您拥有的RGB值中创建一个新的Color
:
Create a new Color
out of the RGB values you have:
Color color = new Color(var1, var2, var3);
然后
- 获取
Class
对象从Color
类使用 - 使用从中获取元素
getEnumConstants()
. - 使用
Arrays.stream()
- 通过调用
toArray()
将流转换为数组. - 使用
[0]
获取该数组的第一个元素.如果没有预定义的颜色与您的颜色匹配,则会抛出ArrayIndexOutOfBoundsException
. - 通过
Enum
获取该颜色的名称的toString()
.
- Get the
Class
object from theColor
class withgetClass()
. - Get the elements from that with
getEnumConstants()
. - Stream it using
Arrays.stream()
- Filter it by calling
filter()
, so it only contains all the enum constants that equal the color you made (there should be either one or zero). - Use
toArray()
to turn the stream into an array. - Get the first element of that array with
[0]
. This will throw anArrayIndexOutOfBoundsException
if there isn't a predefined color matching your color. - Get the name of that color with
Enum
'stoString()
.
String colorName = Arrays.stream(Color.getClass().getEnumConstants())
.filter(c -> c.equals(color))
.toArray()[0]
.toString();
第二种方式
首先,创建一个 HashMap
Color中的>,其中包含您想要的所有颜色:
Second way
First, create a HashMap
of Color
s 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");
然后,从您拥有的RGB值中创建一个新的Color
:
Then, create a new Color
out of the RGB values you have:
Color color = new Color(var1, var2, var3);
最后, get
键color
中colors
中的值:
String colorName = colors.get(color);
这篇关于Java中的颜色类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!