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

标签 java string colors awt

我想通过我的字符串参数设置Polygon的颜色。这是我的代码:

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

最佳答案

您可以使用以下内容:

// 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) );
}

关于java - java awt中从字符串参数到颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59459656/

相关文章:

java - 删除了.gradle目录,现在项目无法刷新

c++ - C++ 中的 Unicode 和 std::string

c++ - 如何在 C++ 中访问 c​​onst char **& 中的数据?

Java - 分割一个字符串,可以用竖线分隔 ("\\I")、逗号分隔 (",")、分号分隔 (";") 等

Android Material 默认颜色

java - 变量可能尚未初始化,不明白为什么

java - 使用 JSTL 标签(点字符)转义 JSP EL

java - 如何在 Spring Kafka Consumer 中跳过损坏的(不可序列化的)消息?

javascript - 如何获得十六进制颜色值而不是 RGB 值?

c - RGBA,每个 channel 8 位大小的 alpha 反转合成,在 C 中