Java Reference
In-Depth Information
Each of these methods updates the current point to be the end of the segment that is added. A path can
consist of several subpaths since a new subpath is started by a moveTo() call. The closePath()
method closes the current subpath by connecting the current point after the last segment to the point
defined by the previous moveTo() call.
Let's illustrate how this works with a simple example. We could create a triangle with the
following statements:
GeneralPath p = new GeneralPath(GeneralPath.WIND _ EVEN _ ODD);
p.moveTo(50.0f, 50.0f); // Start point for path
p.lineTo(150.0f, 50.0f); // Line from 50,50 to 150,50
p.lineTo(150.0f, 250.0f); // Line from 150,50 to 150,250
p.closePath(); // Line from 150,250 back to
start
The first line segment starts at the current position set by the moveTo() call. Each subsequent segment
begins at the endpoint of the previous segment. The closePath() call joins the latest endpoint to the
point set by the previous moveTo() - which in this case is the beginning of the path. The process is
much the same using quadTo() or curveTo() calls and of course you can intermix them in any
sequence you like.
Once you have created a path for a GeneralPath object by calling its methods to add segments to the
path, you can remove them all by calling its reset() method. This empties the path.
The GeneralPath class implements the Shape interface, so a Graphics2D object knows how to
draw a path. You just pass a reference to the draw() method for the graphics context. To draw the
path, p , that we defined above in the graphics context g2D , you would write:
g2D.draw(p); // Draw path p
Let's try an example.
Try It Out - Reaching for the Stars
You won't usually want to construct a GeneralPath object as we did above. You will probably want to
create a particular shape, a triangle or a star say, and then draw it at various points on a component.
You might think you can do this by subclassing GeneralPath , but unfortunately GeneralPath is
declared as final so subclassing is not allowed. However, you can always add a GeneralPath object
as a member of your class. Let's draw some stars using our own Star class. We will use a
GeneralPath object to create the star shown in the diagram.
Search WWH ::




Custom Search