Course Content‎ > ‎Session 7‎ > ‎

Model View Controller

Model View Architecture

Swing graphical controls are based upon a different architecture than AWT, and are termed lightweight components because instead of relying upon the underlying user-interface widgets of the operating system (peers), they handle much of the screen drawing and behavior themselves (this is not the case for the Swing containers). Swing makes use of the Model-View-Controller architecture, which separates the presentation of a component from the underlying data model.

Every user interface component has three characteristics:

    1. It’s contents such as the state of the button or the text in the
       text field.
    2. It’s visual appearance like color, size etc.
    3. It’s behavior i.e. reaction to events.

Model-View-Controller pattern is an object-oriented design pattern. Here, you don’t have a single button class do everything; rather you have the look and feel of a component associated with one object and store the contents in another object. There are three classes, which are implemented: 

    1. The model, which stores the contents
    2. The view, which displays the contents
    3. The controller which handles user input
The model stores the contents and has no user interface. For example, for a button, the content is whether the button is active or not, whether it is currently pushed in or out. The model must implement methods to change the contents and discover what the contents are. The view is the displayed content. In a text field, the model is the string object that holds the current text and view would be the portion of the text displayed in the text field. The model can have multiple views, each showing a different part or aspect of the full contents. The controller handles the user-input events such as keystrokes, mouse clicks. It then decides whether to translate these events into changes in the model or the view. For example, if the user hits a character key in a text box, the controller calls the “insert character” command of the model. The model then tells the view to update itself.

Using Swing components, you don’t need to think about the model-view-controller architecture because each user interface has a wrapper class such as JButton, JTextField, which store the model and the view. When you wish to inquire about the contents of the text in a text field, the wrapper class asks the model and returns the answer to you. When you wish to change the view, the wrapper class forwards that request to the view.

Models are easy to separate and each user interface component has a model class. But the view and the controller are not always clearly separated and are distributed over a number of different classes.

    Interaction between Model, View, and Controller objects