java awt中从字符串参数到颜色

java awt中从字符串参数到颜色,java,string,colors,awt,Java,String,Colors,Awt,我想通过字符串参数为多边形设置颜色。这是我的密码: public void polygon(int xPoints[], int yPoints[], int nPoints, String col) { this.graphics.setColor(col); this.graphics.drawPolygon(xPoints, yPoints, nPoints); } 这是行不通的。因此,经过一些研究后,我尝试添加我的代码Color c=c.web(col) 这也不起作用

我想通过字符串参数为
多边形设置颜色。这是我的密码:

public void polygon(int xPoints[], int yPoints[], int nPoints, String col) {
    this.graphics.setColor(col);
    this.graphics.drawPolygon(xPoints, yPoints, nPoints);

}
这是行不通的。因此,经过一些研究后,我尝试添加我的代码
Color c=c.web(col)

这也不起作用。如何将字符串
col
转换为
color

setColor方法不将字符串作为参数。它需要java.awt.Color。请尝试以下方法:

// add the proper import

import java.awt.Color;

// substitute this line

this.graphics.setColor(Color.RED);
如果用户决定使用字符串,则必须使用映射。将字符串散列为键,并将相应的颜色常量作为值返回。

您可以使用以下命令:

// Fill the map with colors you required
static Map<String, Color> colorMap = Map.ofEntries(Map.entry("RED", Color.RED),
        Map.entry("BLUE", Color.BLUE),
        Map.entry( "BLACK", Color.BLACK),
        Map.entry( "ORANGE", Color.ORANGE));

static Color getColor(String col)
{
        return colorMap.get(col.toUpperCase());
}

public void polygon(int xPoints[], int yPoints[], int nPoints, String col)
{
    this.graphics.drawPolygon(xPoints, yPoints, nPoints);
    this.graphics.setColor( getColor(col) );
}
//用所需的颜色填充地图
静态Map colorMap=Map.of入口(Map.entry(“红色”,Color.RED),
地图条目(“蓝色”,颜色为蓝色),
地图条目(“黑色”,颜色为黑色),
地图输入(“橙色”,颜色为橙色);
静态颜色getColor(字符串颜色)
{
返回colorMap.get(col.toUpperCase());
}
公共空心多边形(int xPoints[],int yPoints[],int nPoints,String col)
{
this.graphics.drawPolygon(xPoints、yPoints、nPoints);
this.graphics.setColor(getColor(col));
}

如果您确定不能直接使用
java.awt.Color
,如在
Color.red
Color.blue
中,可以使用反射从颜色名称中获取相应的颜色,如以下方法所示

Color getColorFromString( String colorStr ) {
    Color color = null;
    try {
        Field field = Class.forName("java.awt.Color").getField(colorStr);
        color = (Color)field.get(null);
    } catch (Exception ignored) {
        // Handle Invalid color
    }
    return color;
}

或者,您可以使用一个预填充的
静态映射
,将颜色字符串作为键,并将相应的颜色对象作为值

你能给出
参数的示例输入吗?是的。例如“红色”试试颜色。红色会有帮助除了主要问题,为什么你甚至有
这个。图形
?该字段何时初始化?谢谢。我之所以使用它,是因为“公共空多边形”在一个绘制一些二维图形的类中。