0

I am trying to create a whack a mole game. I have used swing to create background and add mole images with event listeners which increment a score each time they are clicked, but I am having problems setting whether they should be visible or not. I thought the best way to do this would be to use a timer to set/reset a boolean. This boolean could then be passed to the image's setVisible() constructor. Randomizing the period for which the images are visible would be ideal. I have attempted instantiating a timer and task (inheriting timertask) class, calling timer.vis(vis) which should reset the boolean and then passing task into timer.schedule() but I'm getting a null pointer exception. Am I going about this the wrong way?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
jacka92
  • 55
  • 1
  • 1
  • 7
  • please show us the stacktrace and the relevant code. its too hard to tell where the nullpointer occurs without any of that information – Philipp Sander Oct 28 '14 at 09:27
  • 1
    1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example). 2) Always copy/paste error and exception output! 3) See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) – Andrew Thompson Oct 28 '14 at 09:27
  • Here are some [examples](http://stackoverflow.com/search?tab=votes&q=user%3a230513%20jtogglebutton%20game) using `JToggleButton`. – trashgod Oct 28 '14 at 09:45
  • Use a single timer, but randomise the state – MadProgrammer Oct 28 '14 at 09:50

1 Answers1

0

Well, this will flip a bit with random intervals. You could add code to invoke something in the SwingWorker thread depending on the value of the bit after you change 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);

        // To demonstrate, print the 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());
                // Call SwingWorker thread here
                randomlyFlip(timer, var);
            }
        };
        timer.schedule(task, 500 + (long)(1500 * Math.random()));
    }
}
BarrySW19
  • 3,759
  • 12
  • 26