Java Reference
In-Depth Information
6.8.2 Creating an object to draw
With most of the plain
Graphics
methods you draw a graphic primitive, such as
a line or rectangle, by specifying the coordinates and dimensions in the parameter
list. To draw a line for example, you pass the x, y pixel values (
int
types) of the
beginning and ending points:
g.drawLine (x1, y1, x2, y2);
Java 2D takes a different approach. You create an instance of one of the many
implementing classes of the
java.awt.Shape
interface. There are classes for
lines, rectangles, etc. The positions and dimensions are specified in constructors
or via
set
methods. You then pass the
Shape
reference to the
draw()
method
in
Graphics2D
. This is a much more modular and structured approach to draw-
ing than with
Graphics
(though the latter had the beginnings of this design
with the
drawPolygon()
method, which draws an instance of the
Polygon
class).
The
Shape
interface is implemented by several classes in
java.awt.geom
such as
Line2D
and
Rectangle2D
. (See the
Shape
classes listed in
Figure 6.8.) Most of these classes are abstract. Concrete subclasses provide for
specifying the shape's properties as either
float
or
double
values. For exam-
ple, the
Line2D.Float
and
Line2D.Double
classes use constructors with
float
and
double
type values, respectively, to specify the beginning and end-
ing points of a line.
The code here draws a straight line in the Java 2D framework:
g2.setPaint (Color.BLUE);
Stroke stroke = new BasicStroke (5);
g2.setStroke (stroke);
Line2D.Double line = new Line2D.Double (50.0, 50.0, 100.0,
50.0);
g2.draw (line);
This code draws a blue line, 5 units wide, from
(50.0, 50.0)
to
(100.0,
50.0)
. Similarly, the following code draws a circle:
g2.setRenderingHints (
new RenderingHints (RenderingHints.KEY
-
ANTIALISASING,
RenderingHints.VALUE
-
ANTIALIASING
-
ON));
g2.setPaint (Color.GREEN);
Stroke stroke
=
new BasicStroke (3);
g2.setStroke (stroke);
Ellipse2D.Double ellipse
=
new Ellipse2D.Double (25.0, 25.0,
100.0, 100.0);
g2.draw (ellipse);
Search WWH ::
Custom Search