swing - How to use the Timer class to set/reset a boolean periodically? (Java) -
swing - How to use the Timer class to set/reset a boolean periodically? (Java) -
i trying create whack mole game. have used swing create background , add together mole images event listeners increment score each time clicked, having problems setting whether should visible or not. thought best way utilize timer set/reset boolean. boolean passed image's setvisible() constructor. randomizing period images visible ideal. have attempted instantiating timer , task (inheriting timertask) class, calling timer.vis(vis) should reset boolean , passing task timer.schedule() i'm getting null pointer exception. going wrong way?
well, flip bit random intervals. add together code invoke in swingworker thread depending on value of bit after alter it.
import java.util.timer; import java.util.timertask; import java.util.concurrent.atomic.atomicboolean; public class randombitflip { public static void main(string[] args) throws interruptedexception { final atomicboolean var = new atomicboolean(false); final timer timer = new timer(true); randomlyflip(timer, var); // demonstrate, print value every 200ms for(int x = 0; x < 300; x++) { system.out.println(var.get()); thread.sleep(200); } } private static void randomlyflip(final timer timer, final atomicboolean var) { final timertask task = new timertask() { @override public void run() { var.set(!var.get()); // phone call swingworker thread here randomlyflip(timer, var); } }; timer.schedule(task, 500 + (long)(1500 * math.random())); } }
java swing timer nullpointerexception timertask
Comments
Post a Comment