简体   繁体   English

从预制列表中随机选择一种颜色

[英]randomly select a color from a premade list

I want to randomly select a color from a premade list of colors and I'm not sure how to go about it. 我想从预制的颜色列表中随机选择一种颜色,我不确定该怎么做。 Something like this: 像这样:

String[] randomColor = {"BLUE", "GREEN", "CYAN",
        "RED", "YELLOW", "MAGENTA", "PINK"};
x = (Math.random() * 6)
graphics.setColor(Color.x);

Use Random.nextInt(6) instead. 请改用Random.nextInt(6) But this won't work the way you want. 但这不会按照您想要的方式工作。 You can't reference an object using the string name. 您不能使用字符串名称引用对象。 You will need to put the Color object inside a Color array: Color[] 您需要将Color对象放入Color数组中: Color[]

   Color[] colors = { Color.red, Color.blue, Color.white, Color.cyan, 
                      Color.green, Color.gray, new Color(0xFFAA00) };
   Random random = new Random();
   int x = random.nextInt(colors.length);
   graphics.setColor(colors[x]);

你可以试试这个

randomColor[new Random().nextInt(randomColor.length)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM