Java Reference
In-Depth Information
passed to the method handling the event. However, when you don't have a MouseEvent object available,
you still have the MouseInfo class methods to fall back on.
Now, I return to the subject of how you can define shapes.
DEFINING YOUR OWN SHAPE CLASSES
All the classes that define shapes in Sketcher are static nested classes of the Element class. As I said earlier,
as well as being a convenient way to keep the shape class definitions together, this also avoids possible con-
flicts with the names of standard classes such as the Rectangle class in the java.awt package.
It will be helpful later if each shape class defines a shape with its own origin, like a Swing component.
The process for drawing a shape in a graphics context is to move the origin of the graphics context to the
position recorded for the shape and then draw the shape relative to the new origin. You can start with the
simplest type of Sketcher shape — a class representing a line.
Defining Lines
A line is defined by two points and its color. The origin is the first point on the line, so all line objects have
their first point as (0,0). This is used in all the shape classes in Sketcher, so add a new member to the Ele-
ment class:
static final Point origin = new Point();
The default constructor for Point creates a point at the origin.
You can define the Line class as a nested class in the base class Element as follows:
import java.awt.*;
import java.io.Serializable;
import static Constants.SketcherConstants.*;
import java.awt.geom.*;
public abstract class Element implements Serializable {
// Code defining the base class...
// Nested class defining a line
public static class Line extends Element {
public Line(Point start, Point end, Color color) {
super(start, color);
line = new Line2D.Double(origin.x, origin.y,
end.x - position.x , end.y - position.y);
bounds = new java.awt.Rectangle(
Math.min(start.x ,end.x), Math.min(start.y, end.y),
Math.abs(start.x - end.x)+1, Math.abs(start.y - end.y)+1);
}
// Change the end point for the line
Search WWH ::




Custom Search