Choose Shapes

Along with all the particular knowledge needed to make a GUI program, you also have to organize several interdependent and interacting objects. The Model-View-Controller pattern is a popular organization for GUI's. It consists of:
  1. A Model: a collect of data representing the thing the GUI is about.
  2. A View: an object which produces a visual representation of the Model.
  3. A Controller: an object which operates on the Model, changing its parameters.
As an example, consider a little program which has three buttons, Square, Circle and Triangle, which shows a square, circle or triangle

The controller is both the visual of the three buttons and the listener to the three buttons. It doesn't have to be this way, but it seems clearest in this small example. The controller then does both the visual representation of the controller (the buttons) and the programming of the controller (acting on the model in response to button events).

The model is a very simple object which just acts as an organizer for information. We could have merged it into the controller, but this way the MVC example is most complete.

The view is the actual JPanel that displays the shape. So it is both the program which knows how to render the model as well as the actual component on which the rendering occurs. Like the controller, in complicated examples perhaps the two things are different, but in this simple example it makes a good illustration of concepts if they are the same.

The pattern of communication is that the buttons call-back the controller and the controller then informs the model of changes to the current shape. The model records changes to the current shape and wakes-up (using repaint) the view. The view queries the model for the current shape and draws it.

In order that the controller can talk to the model, the model to the view, and the view to the model, we give a reference to the model on construction of the view and controller. As part of the view's construction, it gives the model a reference to itself; this also happens for the controller. So the communcation is like this:

             --- setShape --->        <--- getShape ---
 controller                    model                      view
                                      ----- repaint --->
The class containing the main method is also the object associated with the frame. Main instantiates in instance of the object of which this main is a method. Seems strange, but it isn't. The main method is static, and can't but touch static variables. Instantiating a ChooseShapes gives a reference to an object which can be used in main.


Burton Rosenberg
13 April 2004