Java Reference
In-Depth Information
import javax.swing.JComponent;
import java.util.*;
import java.awt.*;
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...
}
@Override
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D)g; // Get a 2D device context
for(Element element: theApp.getModel()) { // For each element in the model
element.draw(g2D);
// ...draw the element
}
}
private Sketcher theApp; // The application object
}
Directory "Sketcher 4 drawing sketch line and rectangle elements"
The getModel() method that you implemented in the Sketcher class returns a reference to the Sketch-
erModel object, and because SketcherModel implements the Iterable<> interface, you can use it in a
collection-based for loop to iterate over all the Element objects in the sketch. For each element, you call
its draw() method with g2D as the argument. This draws any type of element because the draw() method
is polymorphic. In this way you draw all the elements that are stored in the model. You should be able to
compile Sketcher successfully, even though the Element class does not have any inner classes defined for
elements.
It's time you put in place the mechanism for creating Sketcher elements. This determines the data that
you use to define the location and dimensions of an element.
DRAWING USING THE MOUSE
You've drawn shapes in examples just using data internal to a program so far. The Sketcher program must
be able to draw a shape from user input and then store the finished shape in the model. You provide mech-
anisms for a user to draw any shape using the mouse.
Ideally, the process should be as natural as possible, so to achieve this you will allow a user to draw by
pressing the left mouse button (more accurately, button 1 — if you have a left-handed setup for the mouse
it is the right button, but still button 1) and dragging the cursor to draw the selected type of shape. So for
Search WWH ::




Custom Search