Java Reference
In-Depth Information
Tip
Some textbooks define a canvas class by subclassing
JComponent
. The problem with
doing that is if you want to set a background in the canvas, you have to write the code
to paint the background color. A simple
setBackground(Color color)
method
will not set a background color in a
JComponent
.
extends JComponent
?
13.1
Suppose that you want to draw a new message below an existing message. Should the
x
-coordinate,
y
-coordinate, or both increase or decrease?
13.2
How is a
Graphics
object created?
13.3
How is the
paintComponent
method invoked? How can a program invoke this
method?
13.4
Why is the
paintComponent
method
protected
? What happens if you change it
to
public
or
private
in a subclass? Why is
super.paintComponent(g)
invoked in line 22 in Listing 13.1?
13.5
Can you draw things on any Swing GUI component? Why should you use a panel as
a canvas for drawings rather than a label or a button?
✓
✓
Check
Point
You can draw strings, lines, rectangles, and ovals in a graphics context.
Key
Point
drawString
The
drawString(String s, int x, int y)
method draws a string starting at the point
(x, y)
, as shown in Figure 13.5a.
The
drawLine(int x1, int y1, int x2, int y2)
method draws a straight line
from point
(x1, y1)
to point
(x2, y2)
, as shown in Figure 13.5b.
drawLine
(getWidth(), 0)
(0, 0)
(getWidth(), 0)
(0, 0)
(x1, y1)
(x, y)
s
is displayed here
(x2, y2)
(0, getHeight())
(getWidth(), getHeight())
(0, getHeight())
(getWidth(), getHeight())
(a)
drawString
F
IGURE
13.5
(a) The
drawString(s, x, y)
method draws a string starting at
(x, y)
. (b) The
drawLine(x1, y1,
x2, y2)
method draws a line between two specified points.
(b)
drawLine
Java provides six methods for drawing the outline of rectangles or rectangles filled with
color. You can draw or fill plain rectangles, round-cornered rectangles, or three-dimensional
rectangles.
The
drawRect(int x, int y, int w, int h)
method draws a plain rectangle, and
the
fillRect(int x, int y, int w, int h)
method draws a filled rectangle. The
parameters
x
and
y
represent the upper-left corner of the rectangle, and
w
and
h
are its width
and height (see Figure 13.6).
The
drawRoundRect(int x, int y, int w, int h, int aw, int ah)
method
draws a round-cornered rectangle, and the
fillRoundRect(int x, int y, int w, int
h, int aw, int ah)
method draws a filled round-cornered rectangle. Parameters
x
,
y
,
w
,
and
h
are the same as in the
drawRect
method, parameter
aw
is the horizontal diameter of the
arcs at the corner, and
ah
is the vertical diameter of the arcs at the corner (see Figure 13.7a).
drawRect
fillRect
drawRoundRect
fillRoundRect