Java Reference
In-Depth Information
CHAPTER 3
■ ■ ■
The Model-View-Controller
Architecture
C hapter 2 explored how to deal with event producers and consumers with regard to Swing
components. We looked at how event handling with Swing components goes beyond the
event-handling capabilities of the original AWT components. In this chapter, we will take the
Swing component design one step further to examine what is called the Model-View-Controller
(MVC) architecture.
Understanding the Flow of MVC
First introduced in Smalltalk in the late 1980s, the MVC architecture is a special form of the
Observer pattern described in Chapter 2. The model part of the MVC holds the state of a
component and serves as the Subject. The view part of the MVC serves as the Observer of the
Subject to display the model's state. The view creates the controller , which defines how the
user interface reacts to user input.
MVC Communication
Figure 3-1 shows how the MVC elements communicate—in this case, with Swing's multiline
text component, the JTextArea . In MVC terms, the JTextArea serves as the view part within the
MVC architecture. Displayed within the component is a Document , which is the model for the
JTextArea . The Document stores the state information for the JTextArea , such as the text contents.
Within the JTextArea is the controller, in the form of an InputMap . It maps keyboard input to
commands in an ActionMap , and those commands are mapped to TextAction objects, which
can modify the Document . When the modification happens, the Document creates a
DocumentEvent and sends it back to the JTextArea .
59
Search WWH ::




Custom Search