在java中按名称获取颜色 [英] getting a color by name in java

查看:677
本文介绍了在java中按名称获取颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用包含 Color 对象的对象模型。

I am working with an object model that contains a Color object.

import java.awt.Color;

public class MyObject {

    ...
    private String color;

    public void setColor( Color c ) ...
    public Color getColor() ...
    ...

}

在json查询的响应中,我留下了一个颜色的物理名称

In the response of a json query, I am left with a physical name of a color


color:blue

"color":"blue"

我知道 Color 对象具有静态,即

I know that the Color object has statics i.e.

Color.blue;

有没有办法将实际颜色名称解码为Color对象?或者我是否需要自己手动将字符串映射到rgb值?

Is there any way to decode actual color names into Color objects? Or would I need to manually map the strings to rgb values myself?

我正在寻找应该是此输出的东西

I am looking for something that should be the output of this

Color c = new Color("blue");

不起作用

推荐答案

如果您的名字与Java的常量相对应,您可以使用反射来映射它们:

If your names correspond to those of Java's constants, you can use reflection to map them:

public static Color getColorByName(String name) {
    try {
        return (Color)Color.class.getField(name.toUpperCase()).get(null);
    } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
        e.printStackTrace();
        return null;
    }
}

这篇关于在java中按名称获取颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆