Java 随机选择4种颜色?
我想随机选择颜色,但只在它们之间(红色、蓝色、绿色和黄色),这里是我正在尝试的一些代码Java 随机选择4种颜色?,java,eclipse,swing,colors,awt,Java,Eclipse,Swing,Colors,Awt,我想随机选择颜色,但只在它们之间(红色、蓝色、绿色和黄色),这里是我正在尝试的一些代码 public class LittleBall extends JPanel { private Random random = new Random(); private float r = random.nextFloat(); private float g = random.nextFloat(); private float b = random.nextFloat(); ..... publ
public class LittleBall extends JPanel {
private Random random = new Random();
private float r = random.nextFloat();
private float g = random.nextFloat();
private float b = random.nextFloat();
.....
public void paint (Graphics g) {
Color randomColor = new Color(r, this.g, b);
g.setColor(randomColor);
}
}
但这只是给世界上的每一种颜色o.o,当然,因为r,g和b变量的下一个浮点值是随机数。但我只想在不同的颜色之间穿插
谢谢。创建一个颜色数组并随机获得一种颜色。
Color[] colors = new Color[] { Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW };
Color randomColor = colors[(int)( Math.random() * 4)];
// or try this one
//Color randomColor = colors[new Random().nextInt(4)];
使用方法如下
Random rand = new Random();
private int r = rand.nextInt(4) + 1;
private int g = rand.nextInt(4) + 1;
private int b = rand.nextInt(4) + 1;
private int y = rand.nextInt(4) + 1;
Color randomColor = new Color(r, g, b,y);
g.setColor(randomColor);
Math.random()
返回一个介于0和1之间的随机数。通过将该值乘以一系列数字,您可以选择最小值和最大值之间的任何值。然后您可能需要将其转换为整数,以获得R、G和/或B的实际值
int r = (int) Math.random() * ( max - min )
将给您指定的min
和max
之间的r
值。因此,您可以按如下方式选择范围:
int r = (int) Math.random() * ( 255 - 100 )
将为您提供介于100和255之间的红色值。当然,你可以在脑子里做减法,然后把
int r = (int) Math.random() * ( 155 )
也可以对绿色和蓝色重复此值
如果愿意,也可以使用浮点值。int将简单地截断结果中的十进制值
<>编辑:查看到目前为止的内容,你必须使用浮点,而不是int。< /P>(int)数学。(4)它可能会生成“0”或“0”,并同时考虑“代码>颜色随机颜色=颜色[数学。随机数] *颜色。长度);<代码>请查看OP问题:
随机选择颜色,但只能选择其中一种颜色(红色、蓝色、绿色和黄色)
这是您的答案吗?@Brj请参阅文档。我很清楚。谢谢,但是如果我想的话,我可以使用随机类?比如@Braj的例子?什么是最好的?你当然可以使用随机类,如果你想。我认为上面的内容更简洁,这就是我推荐它的原因。选择是你的,但=)也考虑洗牌颜色查找表,建议。
int r = (int) Math.random() * ( 155 )