Java Reference
In-Depth Information
Implementing this looks like a job for a GeneralPath object. A GeneralPath object can handle any
number of segments, and you can add to it. You can construct an initial path as soon as you have two points
— which is when you process the first MOUSE_DRAGGED event. You can extend the curve by calling the modi-
fy() method to add another segment to the path using the point that you get for each of the subsequent
MOUSE_DRAGGED events.
TRY IT OUT: The Element.Curve Class
The approach described in the previous section means that the outline of the Curve class is going to be
the following:
import java.awt.*;
import java.io.Serializable;
import static Constants.SketcherConstants.*;
public abstract class Element implements Serializable {
// Code defining the base class...
// Nested class defining a line...
// Nested class defining a rectangle...
// Nested class defining a circle...
// Nested class defining a curve
public static class Curve extends Element {
public Curve(Point start, Point next, Color color) {
super(start, color);
curve = new GeneralPath();
curve.moveTo(origin.x, origin.y);
// Set current position
as origin
curve.lineTo(next.x - position.x, next.y - position.y); // Add
segment
bounds = new java.awt.Rectangle(
Math.min(start.x ,next.x),
Math.min(start.y,
next.y),
Math.abs(next.x - start.x)+1, Math.abs(next.y -
start.y)+1);
}
// Add another segment
public void modify(Point start, Point next) {
curve.lineTo(next.x - position.x, next.y - position.y); // Add
segment
bounds.add(new java.awt.Rectangle(next.x,next.y, 1, 1)); //
Extend bounds
}
// Display the curve
public void draw(Graphics2D g2D) {
g2D.setPaint(color);
// Set the curve
color
Search WWH ::




Custom Search