Main Page

Previous Next

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...
  // Nested class defining a line
  public static class Line extends Element {
    public Line(Point start, Point end, Color color) {
      line = new Line2D.Double(start, end);

    public Shape getShape() { 
      return line; 

    public java.awt.Rectangle getBounds() {
      return line.getBounds();  

    public void modify(Point start, Point last) {
      line.x2 = last.x;
      line.y2 = last.y;

    private Line2D.Double line;

We 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. The constructor has three parameters, the two end points of the line as type Point and the color. Point arguments to the constructor can be of type Point2D or type Point as Point2D is a superclass of Point. After passing the color to the base class constructor, we create the line as a Line2D.Double object. Since this implements the Shape interface, we can return it as type Shape from the getShape() method.

The getBounds() method couldn't be simpler. We just return the Rectangle object produced by the getBounds() method for the object, line. However, note how we have fully qualified the return type. This is because we will be adding a Rectangle class as a nested class to the Element class. When we do, the compiler will interpret the type Rectangle here as our rectangle class, and not the one defined in the java.awt package. You can always use a fully qualified class name when conflicts like this arise.

Try It Out – Drawing Lines

If you have saved the Element class definition as in the same directory as the rest of the Sketcher classes, all you need to do is make sure all the constructor calls other than Element.Line are commented out in the createElement() member of the MouseHandler class, that is an inner class to SketchView. The code for the method should look like this:

    private Element createElement(Point start, Point end) {
      switch(theApp.getWindow().getElementType()) {
        case LINE:
          return new Element.Line(start, end,
JavaScript Editor
 Java Tutorials Free JavaScript Editor