我当前正在尝试将包含颜色的字符串传递到Java paint方法中,但是当前出现错误。有关如何执行此操作的任何提示?
public void paint(Graphics g) {
super.paint(g);
String colorRED = "Color.red";
g.setColor(colorRED);
}
然后,也许您应该让用户输入一个整数值(颜色的RGB值而不是字符串),然后执行类似的操作>]
g.setColor(new Color(rgbValue));
另一方面,如果您确实希望他输入Strings,则可能需要一个将Strings映射为这种颜色的映射图
Graphics g = null; String userInput = null; // Retrieve / initialize the graphics and the user input Map<String, Color> colors = new HashMap<>(); colors.put("RED", Color.RED); colors.put("BLUE", Color.BLUE); // ... add more colors Color color = colors.get(userInput); if (color != null) { g.setColor(color); } else { System.out.println("Sorry, unknown color!"); }
最后,如果您确实希望
String
输入直接引用Color
类中constats定义的颜色,那么您可能可以使用反射并执行类似的操作:
Graphics g;
// Initialize Graphics
String colorString = "CYAN";
try {
Color color = (Color) Color.class.getField(colorString).get(null);
System.out.println(color);
g.setColor(color);
} catch (NoSuchFieldException | IllegalAccessException e) {
System.out.println("Sorry, unknown Color!");
}