Java Reference
In-Depth Information
repaint((Rectangle)rectangle);
}
If rectangle is not null , then we have a reference to a Rectangle object that was provided by the
notifyObservers() method call in the add() method for the SketchModel object. This rectangle
is the area occupied by the new element, so we pass this to the repaint() method for the view to add
just this area to the area to be redrawn on the next call of the paint() method. If rectangle is
null , we call the version of repaint() that has no parameter to redraw the whole view.
Another important operation here is calling the dispose() method for the g2D object. Every graphics
context makes use of finite system resources. If you use a lot of graphics context objects and you don't
release the resources they use, your program will consume more and more resources. Under Windows
for instance you may eventually run out, your computer will stop working, and you'll have to reboot.
When you call dispose() for a graphics context object it can merely no longer be used, so we set g2D
back to null to be on the safe side.
A reminder about a potential error in using adapter classes - be sure to spell the
method names correctly. If you don't, your method won't get called, but the base class
member will. The base class method does nothing so your code won't work as you
expect. There will be no warning or error messages about this because your code will
be perfectly legal - though quite wrong. You will simply have added an additional and
quite useless method to those defined in the adapter class.
We have implemented all three methods that we need to draw shapes. We could try it out if only we
had a shape to draw.
Defining Our Own Shape Classes
All the classes that define shapes in Sketcher will be static nested classes of the Element class. As we
have already said, as well as being a convenient way to keep our shape class definitions together, this
will also avoid possible conflict with classes such as the Rectangle class in the Java class library.
We can start with the simplest - a class representing a line.
Defining Lines
A line will be defined by two points and its color. We can define the Line class as a nested class in the
base class Element , as follows:
import java.awt.Color;
import java.awt.Shape;
import java.awt.Point;
import java.awt.geom.*; // For classes defining shapes
public abstract class Element {
// Code defining the base class...
Search WWH ::




Custom Search