Java Reference
In-Depth Information
gives the current color in use by the graphics context object. To obtain the back-
ground and foreground colors for a component, use
Color bg
=
getBackground ();
Color fg
=
getForeground ();
6.7 Drawing with the
Graphics
class
Here we illustrate drawing operations using the methods available in the
Graph-
ics
class. The
Graphics2D
class offers more capabilities, which we discuss
briefly in Section 6.8. Drawing typically begins with an invocation of the
set-
Color (Color c)
method in
Graphics
that tells the graphics context what
color to use when it draws a line or primitive shape like a rectangle or when
it fills a primitive shape with a solid color. The methods in the
Graphics
class for drawing and filling include the following (all parameters are
int
types):
drawLine (x1, y1, x2, y2)
- draws a line between points
(x1,y1)
and
(x2,y2).
drawRect (x, y, width, height)
and
fillRect (x, y, width,
height)
- draws (fills) a rectangle,
(x,y)
are the coordinates of the top-left corner,
the bottom-right corner will be at
(x+width,y+height)
.
drawOval (x, y, width, height)
and
fillOval (x, y, width,
height)
- draws (fills) an oval
bounded
by
the rectangle specified by these
parameters.
draw3DRect (x, y, width, height)
and
fill3DRect (x, y, width,
height)
- draws (fills) a rectangle with shaded sides that provide a 3-D appearance.
drawRoundRect (x, y, width, height)
and
fill3DRect (x, y,
width, height)
- draws (fills) a rectangle with rounded corners.
drawPolyline (int[] x, int[] y, int n)
- draws lines connecting the n
points given by the x and y arrays.
drawPolygon (int[] x, int[] y, int n)
- draws lines connecting the
points given by the x and y arrays. Connects the last point to the first if they are not
already the same point.
Note that
Graphics
does not provide a method to set the width of a line. The line
is always one pixel wide and continuous (i.e. no dot-dash options). Nevertheless,
these methods are simple and often convenient to use and can be used along with
the
Graphics2D
methods.
Figure 6.6
Example
DrawApplet
uses drawing
methods in the
Graphics
class.
6.7.1 Drawing demo
The applet
DrawApplet
shown in Figure 6.6 illustrates some of the drawing
methods from the
Graphics
class. The applet first creates a
JPanel
subclass
Search WWH ::
Custom Search