CIT 591 Assignment 8: Important information for GUI developers
Fall 2003, David Matuszek

For some reason, I thought that it was not necessary to create a separate Thread for this assignment. I was wrong. I'll lecture on the topic, but meanwhile, here's what you need to do.

You need to say that Model class implements Runnable, and this means you need a public void run() method. Mine looks like this, and you are welcome to copy it and use it as is, or modify it to fit your needs..

class Model extends Observable implements Runnable {
    ...
    public void run() {
        while (running) { // this flag is set by the controller
            makeOneStep(); // or whatever you called your method
            this.setChanged();
            this.notifyObservers();
            try { Thread.sleep(20); } // pause for a while
            catch (InterruptedException e) {}
        }
    }

The makeOneStep() method, in my example, moves a "bouncing ball" a little further along its path.

When the user clicks the Start button, you have to set the running flag to true, and you have to create a new Thread like this:

 Thread thread = new Thread(model);
thread.start();

(model is the name of my Model object). When the user clicks the Stop button, you have to cause the run() method to exit, which in turn causes the Thread to die:

model.running = false; 

You should be sure not to create extra threads; one Model thread at a time is what you need. You can ensure this by selectively enabling the Start and Stop buttons; I did it with a single button that acts as a toggle.


One of those nasty little details that I had forgotten to mention: You can only get the height and width of components after the init() method finishes; earlier than that, you will just get zeros. A good place to get the height and width of your drawing area is in the start() method.


There's a complete SimpleAnimation example at animation.zip.