This site requires JavaScript, please enable it in your browser!
Greenfoot back
Canning
Canning wrote ...

2011/9/10

Timer

Canning Canning

2011/9/10

#
I am wanting to call a method every 10 seconds, how do I go about this? I have tried to create a separate class with this code: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import javax.swing.Timer; import java.awt.event.*; import java.util.*; public class TimerDemo implements ActionListener { Timer t = new Timer(10000,this); TimerDemo() { t.start(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == t) { System.out.println ("Testing"); } } } This works, but I am not sure how to reference the world to call a public method. How can I do this please? Or is there a better way to call a method every 10 seconds? thanks
mjrb4 mjrb4

2011/9/10

#
You're using multiple threads here, which opens up a whole new can of worms in terms of subtle bugs and is unsupported by Greenfoot itself (which does everything from a single thread.) A much simpler way would be to use an actor with a field to store the "initial time" (using System.currentTimeMillis()) and check the value with System.currentTimeMillis() every act loop. If the current time is more than 10 seconds (10,000ms) after the stored field, you call your method, reset the field to the current time and loop back round again.
AwesomeNameGuy AwesomeNameGuy

2011/9/10

#
I've used timer classes in my code with no problems. What mjrb4 said should work too, Anyway, to refrence the world I think all you need to do is delcare it for example ExampleWorld e; and then somewhere later in your code do e = (ExampleWorld) getWorld(); and there's your refrence. Don't do this in a constructor though because if I remeber it gives a null pointer exception for some reason.
Canning Canning

2011/9/11

#
Thanks guys. I will use the System.currentTimeMillis() approach.
You need to login to post a reply.