Java Reference
In-Depth Information
You can define the view class as a component by deriving it from the JComponent class. This builds in all
the methods for operating as a Swing component and you are able to override any of these when necessary.
You will be using Swing components throughout, so when I refer to a component, I mean a Swing com-
ponent. The view class also needs to implement the Observer interface so that you can register it with the
model to receive notification when the model changes. Here's the outline:
import javax.swing.JComponent;
import java.util.*;
public class SketcherView extends JComponent implements Observer {
public SketcherView(Sketcher theApp) {
this.theApp = theApp;
}
// Method called by Observable object when it changes
public void update(Observable o, Object rectangle) {
// Code to respond to changes in the model...
}
private Sketcher theApp;
// The application object
}
Directory "Sketcher 1 drawing a 3D rectangle"
The view needs access to the model to display it, but rather than store a reference to the model in the
view, the constructor has a parameter to enable the application object to be passed to it. The view object is
able to use the application object to access the model object, and the application window if necessary.
The view is registered as an observer for the model. If a completely different object represents the model
because, for example, a new file is loaded, the view object is automatically notified by the model that it has
changed and is able to respond by redrawing the view.
To integrate a model and its view into the Sketcher application, you just need to add some code to the
Sketcher class that defines the application object:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Sketcher {
public static void main(String[] args) {
theApp = new Sketcher(); // Create the
application object
SwingUtilities.invokeLater(new Runnable() {
public void run() {
theApp.createGUI(); // Call GUI creator
Search WWH ::




Custom Search