O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required