使第二辆车的颜色随机变成JAVA

时间:2015-12-01 22:50:18

标签: java colors graphics2d

每当我点击屏幕时我都会制作每辆车,但第二辆车不会改变颜色。我为我的车做了随机颜色,但我不知道为什么第二辆车不会改变。请帮帮我。

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 set Color中出错,但它想改变颜色。或者Java有什么方法可以删除当前的颜色?

2 个答案:

答案 0 :(得分:3)

当你打电话

Color randomColor2 = new Color(red, green, blue);

红色,绿色和蓝色仍然具有相同的值。 你必须再次调用randomGenerator。

red = randomGenerator.nextInt(256);
green = randomGenerator.nextInt(256);
blue = randomGenerator.nextInt(256);
Color randomColor2 = new Color(red, green, blue);

答案 1 :(得分: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

redbluegreen的值永远不会改变,因此颜色也不会改变。