Reputation: 18753
I am trying to store the Color values in Java Array but I know that these values are stored as strings,
String[] colorarray = {"Color.yellow","Color.red","Color.blue"};
Now, I couldn't access this array element to set the color, i.e
g.setColor(colorarray[0]);
Because all the values in the array are strings. How could I convert these values to the constants ?
Upvotes: 0
Views: 147
Reputation: 6207
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[] 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.XXX
where XXX
is the name of your color. (This could also be done using a big if-else block but that wouldn't be as clean)One other quick note - variable names in Java are, by convention, in camelCase starting with a lower-case letter. This helps make your code more readable. (Class names are CamelCase, package names are lower.case)
Upvotes: 2
Reputation: 159754
Use
Color[] colorArray = {Color.YELLOW, Color.RED, Color.BLUE};
Upvotes: 11
Reputation: 205
Straightforward, use this :
Color[] colorarray = {Color.YELLOW, Color.RED, Color.BLUE};
Upvotes: 7