MVC is a well known object-oriented user interface design decomposition that dates back to the late 1970s. Components are broken down into three parts: a model, a view, and a controller. Each Swing component is based on a more modern version of this design. Before we discuss how MVC works in Swing, we need to understand how it was originally designed to work.
Figure 1.3 Model-view-controller architecture
The model is responsible for maintaining all aspects of the component state. This includes, for example, such values as the pressed/unpressed state of a push button, a text component’s character data and information about how it is structured, etc. A model may be responsible for indirect communication with the with the view and the controller. By indirect we mean that the model does not ‘know’ its view and controller–it does not maintain or retreive references to them. Instead the model will send out notifications or broadcasts (what we know as events). In figure 1.3 this indirect communication is represented by dashed lines.
The view determines the visual representation of the component’s model. This is a component’s “look.” For example, the view displays the correct color of a component, whether the component appears raised or lowered (in the case of a button), and the rendering of a desired font. The view is responsible for keeping its on-screen representation updated and may do so upon receiving indirect messages from the model, or direct messages from the controller.
The controller is responsible for determining whether the component should react to any input events from input devices such as the keyboard or mouse. The controller is the “feel” of the component, and it determines what actions are performed when the component is used. The controller can receive direct messages from the view, and indirect messages from the model.
For example, suppose we have a checked (selected) checkbox in our interface. If the controller determines that the user has performed a mouse click it may send a message to the view. If the view determines that the click occurred on the checkbox it sends a message to the model. The model then updates itself and broadcasts a message, which will be received by the view(s), to tell it that it should update itself based on the new state of the model. In this way, a model is not bound to a specific view or controller, allowing us to have several views and controller’s manipulating a single model.