PDA

View Full Version : Help with using a timer


Pieterman
03-21-2005, 07:14 PM
hey i am having trouble with using a timer in my java game. I want to activate a timer with a command of a key and then every 5 seconds i want the color of the background of the panel to change.
Could anyone help me get this started.
any basic coding would be helpfull
thanks Pieterman

hinokata
03-23-2005, 08:13 AM
The easiest way to do this would be to have a timer thread that sleeps X amount of time and then wakes up and changes the background color and then goes back to sleep.

Please note I said this would be the easiest, NOT the best. You will still have ~some~ time skew, but it shouldn't be enough for you to notice.

Pieterman
03-23-2005, 11:59 AM
do you know of any good tutorials which would help me with the timer thread

hinokata
03-23-2005, 12:27 PM
Not really, no. :(
Here is puesdo code that you could use to get you started:


public class PuesdoSample
{
public PuesdoSample( String args[] )
{
Thread t = new Thread( new Timer() );
t.start();
/* Go on with your other code here */
}

private class extends Thread /* or use implements Runnable */
{
public Timer()
{
/* Initialize stuff here */
}

public void run()
{
while( true )
{
Thread.sleep( 5000 ); /* Sleep for 5 minutes */
someMethodThatChangesBackgroundColor();
}
}
}

public static void main( String args[] )
{
new PuesdoSample( args );
}
}


Bear in mind, this is very rough and will need to be sketched in. Also note that this loop forever, so you may need a callback or a boolean value to let the timer loop know when it can exit. I also make no promises that this will compile as it was all written within the confines of this tiny little window. :)

Pieterman
03-29-2005, 08:48 PM
Thanks alot