19.8. Defining Your Own Shape Classes
All the classes that define shapes in Sketcher will be 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 will also avoid possible conflicts with the names of standard classes such as the Rectangle class in the java.awt package.
You can start with the simplest type of Sketcher shape—a class representing a line.
19.8.1. Defining Lines
A line will be defined by two points and its color. You 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.Line;
public abstract class Element {
// 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(color);
line = new Line2D.Double(start, end);
}
// Method to return the line as a Shape reference
public Shape getShape() {
return line;
}
// Obtain the rectangle bounding the line
public java.awt.Rectangle getBounds() {
return line.getBounds();
}
// Change the end point for the line
public void modify(Point start, Point last) {
line.x2 = last.x;
line.y2 = last.y;
}
private Line2D.Double line;
}
}
You have to specify the Line class as static to avoid a dependency on an Element object being available. The Element class is abstract, so there's no possibility of creating objects of this type. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access