Java Reference
In-Depth Information
All of the objects representing attributes are stored as references within a
Graphics2D
object.
Therefore, you must always call a
setXXX()
method to alter an attribute in a graphics context, not try
to modify an external object directly. If you alter an object externally that has been used to set an
attribute, the results are unpredictable.
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 change the antialiasing
that is applied by calling one of the two
setRenderingHints()
methods for a graphics
context. We will not be going 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,
we'll explore how to apply new attributes to a graphics context piecemeal where it is relevant to the
various examples we will create.
Rendering Operations
The following basic methods are available to a
Graphics2D
object for rendering various kinds of entity:
Method
Description
draw(Shape shape)
Renders a shape using the current attributes for the graphics
context. We will be discussing what a shape is next.
fill(Shape shape)
Fills a shape using the current attributes for the graphics
context. We will see how to do this later in this chapter.
drawString(String text)
Renders a text string using the current attributes for the
graphics context. We will be applying this further in the
next chapter.
drawImage()
Renders an image using the current attributes for the
graphics context. This is quite a complicated operation so
we won't be getting very far into this.
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, so to use them in
a class we will need an
import
statement for this package at the beginning of the class file. You can
add one to
SketchView.java
right now if you like. While the classes that define shapes are in
java.awt.geom
, the
Shape
interface is defined in
java.awt
, so you will usually need to import
class names from both packages into your source file.
Any class that implements the
Shape
interface defines a shape - visually it will be some composite of
straight lines and curves. Straight lines, rectangles, ellipses and curves are all shapes.