Java Reference
In-Depth Information
NOTE
You can also affect how the rendering process deals with “jaggies" when drawing
lines. The process to eliminate jaggies on sloping lines is called
antialiasing,
and you can
changetheantialiasing thatisapplied bycalling oneofthetwo
setRenderingHints()
meth-
ods for a graphics context. I don't go into this aspect of drawing further, though.
There's a huge amount of detail on attributes under the covers. Rather than going into all that here, you
explore how to apply new attributes to a graphics context piecemeal where it is relevant to the various ex-
amples you create.
Rendering Operations
You have the following basic methods available with a
Graphics2D
object for rendering various kinds of
graphic entities:
•
draw(Shape shape)
renders a shape using the current attributes for the graphics context. I discuss
what a shape is next.
•
fill(Shape shape)
fills a shape using the current attributes for the graphics context. You see
how to do this later in this chapter.
•
drawString(String text)
renders a text string using the current attributes for the graphics con-
text. You apply this further in the next chapter.
This is very much a subset of the methods available in the
Graphics2D
class. I concentrate on those that
draw shapes and strings that I have identified here. Let's see what shapes are available; they'll help make
Sketcher a lot more useful.
SHAPES
Classes that define geometric shapes are contained in the
java.awt.geom
package, but the
Shape
interface
that these classes implement is defined in
java.awt
. Objects that represent shapes are often passed around
as references of type
Shape
, so you often need to import class names from both packages into your source
file. Any class that implements the
Shape
interface defines a shape, and visually a shape is some composite
of straight lines and curves. Straight lines, rectangles, ellipses, and curves are all shapes.
A graphics context knows how to draw objects of a type that implements the
Shape
interface. To draw
a shape on a component, you just need to pass the object defining the shape to the
draw()
method for the
Graphics2D
object for the component. To explore this in detail, I split the shapes into three groups: straight
lines and rectangles, arcs and ellipses, and freeform curves. First, though, you must take a look at how points
are defined.
Classes Defining Points
Two classes in the
java.awt.geom
package define points:
Point2D.Float
and
Point2D.Double
. From the
class names you can see that these are both inner classes to the
Point2D
class, which also happens to be
an abstract base class for both classes, too. The
Point2D.Float
class defines a point from a pair of (
x,y
)
coordinates of type
float
, whereas the
Point2D.Double
class defines a point as a coordinate pair of type
double
. The
Point
class in the
java.awt
package also defines a point, but in terms of a coordinate pair of