Java 使第二辆车不同的随机颜色
每当我点击屏幕时,我都会创建每一辆车,但第二辆车的颜色不会改变。我为我的车随机涂上颜色,但我不知道为什么第二辆车没有改变。请帮帮我Java 使第二辆车不同的随机颜色,java,colors,graphics2d,Java,Colors,Graphics2d,每当我点击屏幕时,我都会创建每一辆车,但第二辆车的颜色不会改变。我为我的车随机涂上颜色,但我不知道为什么第二辆车没有改变。请帮帮我 public void paintComponent(Graphics g) { Random randomGenerator = new Random(); int red = randomGenerator.nextInt(256); int green = randomGenerator.nextInt(256); int bl
public void paintComponent(Graphics g)
{
Random randomGenerator = new Random();
int red = randomGenerator.nextInt(256);
int green = randomGenerator.nextInt(256);
int blue = randomGenerator.nextInt(256);
Graphics2D g2 = (Graphics2D) g;
if (drawCar)
{
Color randomColor = new Color(red, green, blue);
g2.setColor(randomColor);
int x = 1;
int carSpeed = 1;
int w = getWidth();
//create the car from draw class
if (x == 1 )
{
x = lastX + carSpeed;
if (x == w - 60)
{
x = lastX - 730;
}
lastX = x;
}
Car car1 = new Car(x,320);
car1.draw(g2);
}
if (drawCar2)
{
Color randomColor2 = new Color(red, green, blue);
g2.setColor(randomColor2);
int x = 1;
int carSpeed = 1;
int w = getWidth();
//create the car from draw class
if (x == 1 )
{
x = lastX2 + carSpeed;
if (x == w - 60)
{
x = lastX2 - 730;
}
lastX2 = x;
}
Car car2 = new Car(x,320);
car2.draw(g2);
}
}
我想我在g2设置的颜色可能是错误的,但它应该改变颜色。或者Java有什么方法删除当前颜色吗?当你调用
Color randomColor2 = new Color(red, green, blue);
红色、绿色和蓝色仍然具有相同的值。
你必须再次调用你的随机发生器
red = randomGenerator.nextInt(256);
green = randomGenerator.nextInt(256);
blue = randomGenerator.nextInt(256);
Color randomColor2 = new Color(red, green, blue);
当你打电话时
Color randomColor2 = new Color(red, green, blue);
红色、绿色和蓝色仍然具有相同的值。
你必须再次调用你的随机发生器
red = randomGenerator.nextInt(256);
green = randomGenerator.nextInt(256);
blue = randomGenerator.nextInt(256);
Color randomColor2 = new Color(red, green, blue);
理论上你确实改变了g的颜色。但您将其设置为相同的颜色:
Color randomColor = new Color(red, green, blue); //color for car 1
...//some other drawing stuff
Color randomColor = new Color(red, green, blue); //color for car 2
红色、蓝色和绿色的值永远不会改变,颜色也不会改变。理论上,你确实改变了g的颜色。但您将其设置为相同的颜色:
Color randomColor = new Color(red, green, blue); //color for car 1
...//some other drawing stuff
Color randomColor = new Color(red, green, blue); //color for car 2
红色、蓝色和绿色的值永远不会改变,颜色也不会改变