我想通过我的String参数为Polygon
设置颜色。这是我的代码:
public void polygon(int xPoints[], int yPoints[], int nPoints, String col) {
this.graphics.drawPolygon(xPoints, yPoints, nPoints);
this.graphics.setColor(col);
}
这不起作用。因此,经过研究后,我尝试添加代码Color c = c.web(col);
而且这也不起作用。如何将字符串col
转换为color
?
setColor方法不使用String作为参数。它需要java.awt.Color。请尝试以下方法:
// add the proper import
import java.awt.Color;
// substitute this line
this.graphics.setColor(Color.RED);
如果确定要使用字符串,则必须使用映射。将您的String哈希为键,并返回相应的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.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;
}
或者,您可以预先填充static Map<String, Color>
,其中将颜色字符串作为键,并将相应的Color对象作为值。
替换
this.graphics.setColor(col);
with
this.graphics.setColor(Enum.valueOf(java.awt.Color.class, col));
其中Color
为java.awt.Color
。