change color randomly of object
Hi,
I wrote a small application simulating a road traffic. I am using threads to do the animation.
this is the code:
publicclass TestProjectextends Frameimplements Runnable
{
publicstaticint frame;// int variable for frame (animation)
int delay = 100;// delay for animation
Thread animator, light;// thread name
/**
* Create a thread and start it.
*/
publicvoid start()
{
animator =new Thread(this);// create new thread
animator.start();// start thread
}
/**
* This method is called by the thread that was created in
* the start method. It does the main animation.
*/
publicvoid run()
{
// Remember the starting time
long tm = System.currentTimeMillis();// get time (ms) and store it in tm
while (Thread.currentThread() == animator)
{
// Display the next frame of animation.
if (frame==(200*roadArrangement.size()+50))// if object reaches "end" reset
{
frame =-50;// "reset" frame
}
repaint();// repaint object
// Delay depending on how far we are behind.
try
{
tm += delay;// delay
Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
}
catch (InterruptedException e)// catch exception for thread
{
System.out.println("error in thread interrupt!");
break;
}
frame++;// Advance the frame
}
}// end of run
/**
* Set the animator variable to null so that the
* thread will exit before displaying the next frame.
*/
publicvoid stop()
{
animator =null;
}
/**
* Paint a frame of animation.
*/
publicvoid paint(Graphics g)
{
for(int i = 0; i < roadArrangement.size(); i++)
{
String tempType = roadArrangement.elementAt(i).toString();
char roadType = tempType.charAt(0);
g.setColor(Color.darkGray);
if(roadType =='r')
{
g.setColor(Color.darkGray);
g.fill3DRect(10+(i*210),100,210,60,true);
}
elseif(roadType =='j')
{
g.setColor(Color.darkGray);
g.fill3DRect(10+(i*210),100,210,60,true);
g.fill3DRect(85+(i*210),160,60,70,true);
g.fill3DRect(85+(i*210),30,60,70,true);
g.setColor(Color.green);// traffic light color
g.fillOval(10+(i*210)+50,30+100,10,10);// traffic light
Color clr = g.getColor();
int red = clr.getRed();
if((frame == (10+(i*210)+50))&&(red==255))
{
stop();// stop thread to stop cars
System.out.println("STOP");
}
}
}
}
In the code I have "oval" traffic lights where I set the colours.
Now, what I want to do is that traffic lights change independently and randomly their colour so that cars stop and drive.
How can I do this? Will I need a second thread? If yes, how to implement that?
thanks in advance.

