Java Reference
In-Depth Information
import javax.swing.JComponent;
import java.util.Observer;
import java.util.Observable;
class SketchView extends JComponent implements Observer {
public SketchView(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
}
The view is definitely going to need access to the model in order to display it, but rather than store a
reference to the model, the constructor has a parameter to enable the application object to be passed to
it. By storing the application object in the view, rather than a reference to the model, and adding a
method to the application object to return a reference to the model, we make the view object
independent of the model object. If a completely different object represents the model because, for
example, a new file is loaded, we don't need to change the view object. As long as the view object is
registered as an observer for the new model, the view will automatically redraw the new sketch when it
is notified by the model that it has changed.
To integrate a model and its view into the Sketcher application, we just need to add some code to the
Sketcher class:
import java.awt.*;
import java.awt.event.*;
import java.util.Observer;
import java.util.Observable;
public class Sketcher {
public static void main(String[] args) {
theApp = new Sketcher(); // Create the application object
theApp.init(); // ... and initialize it
}
public void init() {
window = new SketchFrame("Sketcher", this); // Create the app window
Toolkit theKit = window.getToolkit(); // Get the window toolkit
Dimension wndSize = theKit.getScreenSize(); // Get screen size
// Set the position to screen center & size to 2/3 screen size
window.setBounds(wndSize.width/6, wndSize.height/6, // Position
2*wndSize.width/3, 2*wndSize.height/3); // Size
window.addWindowListener(new WindowHandler()); // Add window listener
sketch = new SketchModel(); // Create the model
Search WWH ::




Custom Search