Java Reference
In-Depth Information
You can draw custom shapes on a GUI component.
Key
Point
Suppose you want to draw shapes such as a bar chart, a clock, or a stop sign, as shown in
Figure 13.1. How do you do so?
Problem
(a)
(b)
(c)
F
IGURE
13.1
You can draw shapes using the drawing methods in the
Graphics
class.
This chapter describes how to use the methods in the
Graphics
class to draw strings,
lines, rectangles, ovals, arcs, polygons, and images, and how to develop reusable GUI compo-
nents.
Each GUI component has a graphics context, which is an object of the
Graphics
class. The
Graphics
class contains the methods for drawing various shapes.
Key
Point
The
Graphics
class provides the methods for drawing strings, lines, rectangles, ovals, arcs,
polygons, and polylines, as shown in Figure 13.2.
Think of a GUI component as a piece of paper and the
Graphics
object as a pencil or
paintbrush. You can apply the methods in the
Graphics
class to draw graphics on a GUI
component.
To paint, you need to specify where to paint. Each component has its own coordinate sys-
tem with the origin (
0
,
0
) at the upper-left corner. The
x-
coordinate increases to the right, and
the
y
-coordinate increases downward. Note that the Java coordinate system differs from the
conventional coordinate system, as shown in Figure 13.3.
The
Graphics
class-an abstract class—provides a device-independent graphics interface
for displaying figures and images on the screen on different platforms. Whenever a compo-
nent (e.g., a button, a label, or a panel) is displayed, the JVM automatically creates a
Graphics
object for the component on the native platform and passes this object to invoke
the
paintComponent
method to display the drawings.
The signature of the
paintComponent
method is as follows:
paintComponent
protected void
paintComponent(Graphics g)
This method, defined in the
JComponent
class, is invoked whenever a component is first dis-
played or redisplayed.
To draw on a component, you need to define a class that extends
JPanel
and overrides its
paintComponent
method to specify what to draw. Listing 13.1 gives an example that draws
a line and a string on a panel, as shown in Figure 13.4.