Simple Animation Example

Your browser is ignoring the <APPLET> tag!

Here is an example of a simple animation illustrating the use of threads and two design patterns: model-view-controller (MVC) and observer-observable. Following the MVC pattern, the program is dived into three parts: the model, the view and the controller. Since this is such a simple example, each is coded as a single class. Because we would like the simulation to run and still be able to handle user interface events (e.g., clicking on the STOP button), the model runs in one thread and the controller in another.

The Model does the work of running the simple simulation of the bouncing ball. The model class extends the observable class and implements the runnable interface. Whenever it does something that another class might be interested in, it "broadcasts" the fact to all other classes that might be interested. Note that the Model does not need to know or care anything about which other classes, if any, might be interested, so it remains completely independent of those classes.

The View's job is to display the current state of the model. It has to observe the Model class; it does this by implementing the observer interface and defining the required update method, which will automatically be called any time a class that it is observing broadcasts something.

The Controller in this program sets things up, including a single control -- a button to run or stop the simulation, depending on the state it is in. It sets up the GUI, create the Model and the View, and registers the View as an observer of the Model. Because we are using the observer-observable pattern, the model takes on the responsibility of informing the view that it has changed so the view can redisplay the state.

The applet html code is here.

This code is available as a BlueJ project in a zip file.