Java Reference
In-Depth Information
Directory "Sketcher 4 drawing sketch line and rectangle elements"
If tempElement is not null in the mouseDragged() method, an element already exists, so you draw over
it in the application window by calling its draw() method. Because you are in XOR mode, this effectively
erases the element. You then modify the existing element to incorporate the latest cursor position by calling
the method modify() for the element object. Finally, you draw the latest version of the element that is ref-
erenced by tempElement .
You can implement the createElement() method as a static member of the Element class. The para-
meters for the method are the current element type and color and the two points that are used to define each
element. Here's the code:
public static Element createElement(int type, Color color, Point start, Point
end) {
switch(type) {
case LINE:
return new Line(start, end, color);
case RECTANGLE:
return new Rectangle(start, end, color);
case CIRCLE:
return new Circle(start, end, color);
case CURVE:
return new Curve(start, end, color);
default:
assert false;
// We should never get to here
}
return null;
}
Directory "Sketcher 4 drawing sketch line and rectangle elements"
Because you refer to the constants that identify element types here, you must import the static members
of the SketcherConstants class that you defined in the Constants package into the SketcherView.java
source file. Add the import statement to the Element class file:
import static Constants.SketcherConstants.*;
The createElement() method returns a reference to a shape as type Element . You determine the type
of shape to create by retrieving the element type ID stored in the SketcherFrame class by the menu item
listeners that you put together in the previous chapter.
The switch statement in the createElement() method selects the constructor to be called, and as you
see, they are all essentially of the same form. If the code falls through the switch with an ID that you haven't
provided for, you return null . Of course, none of these shape class constructors exists in the Sketcher pro-
gram yet, so if you want to try compiling the code you have so far, you need to comment out each of the
return statements. Because you are calling the constructors from a static method in the Element class, the
element classes must be static, too. You implement these very soon, but first let's add the next piece of
mouse event handling that's required — handling button release events.
Search WWH ::




Custom Search