[英]How to access Array elements as constants - Java
I am trying to store the Color values in Java Array but I know that these values are stored as strings, 我正在尝试将Color值存储在Java Array中,但我知道这些值存储为字符串,
String[] colorarray = {"Color.yellow","Color.red","Color.blue"};
Now, I couldn't access this array element to set the color, ie 现在,我无法访问此数组元素来设置颜色,即
g.setColor(colorarray[0]);
Because all the values in the array are strings. 因为数组中的所有值都是字符串。 How could I convert these values to the constants ? 如何将这些值转换为常数?
采用
Color[] colorArray = {Color.YELLOW, Color.RED, Color.BLUE};
直接使用此方法:
Color[] colorarray = {Color.YELLOW, Color.RED, Color.BLUE};
If you have control over the array, by all means change it to just be an array of Color
s as suggested by several other people. 如果您对数组有控制权,请务必将其更改为仅由Color
的数组,这是其他几个人建议的。
Color[] colorArray = {Color.YELLOW, Color.RED, Color.BLUE};
If you don't have control over the array and you have to use it as-is, you'll need to do one of two things: 如果您无法控制数组,而必须按原样使用它,则需要执行以下两项操作之一:
Color
class (a quick Google search will give you plenty of examples on how to do this so I won't go into it here) 使用反射来访问Color
类的静态成员(快速的Google搜索将为您提供有关如何执行此操作的大量示例,因此在这里我不再赘述) Color.XXX
where XXX
is the name of your color. 在字符串上创建Java 7 switch语句,以将数组中的每个可能的颜色值解释为Color.XXX
,其中XXX
是您的颜色名称。 (This could also be done using a big if-else block but that wouldn't be as clean) (这也可以使用一个大的if-else块来完成,但是那样不干净) One other quick note - variable names in Java are, by convention, in camelCase starting with a lower-case letter. 另一个快速说明-按照惯例,Java中的变量名以驼峰大写字母开头。 This helps make your code more readable. 这有助于使您的代码更具可读性。 (Class names are CamelCase, package names are lower.case) (类名称为CamelCase,包名称为小写)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.