Java Reference
In-Depth Information
2.
Whenever a component (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.
3.
Normally you use
JPanel
as a canvas. To draw on a
JPanel
, you create a new class
that extends
JPanel
and overrides the
paintComponent
method to tell the panel
how to draw graphics.
4.
Invoking
super.paintComponent(g)
is necessary to ensure that the viewing area
is cleared before a new drawing is displayed. The user can request the component to
be redisplayed by invoking the
repaint()
method defined in the
Component
class.
Invoking
repaint()
causes
paintComponent
to be invoked by the JVM. The user
should never invoke
paintComponent
directly. For this reason, the protected visi-
bility is sufficient for
paintComponent
.
5.
The
Component
class has the
setBackground
,
setForeground
, and
setFont
methods. These methods are used to set colors and fonts for the entire component. If
you want to draw several messages in a panel with different colors and fonts, you
have to use the
setColor
and
setFont
methods in the
Graphics
class to set the
color and font for the current drawing.
6.
FontMetrics
can be used to compute the exact length and width of a string,
which is helpful for measuring the size of a string in order to display it in the right
position.
7.
To display an image, first create an image icon. You can then use
ImageIcon
's
getImage()
method to get an
Image
object for the image and draw the image using
the
drawImage
method in the
java.awt.Graphics
class.
T
EST
Q
UESTIONS
P
ROGRAMMING
E
XERCISES
Sections 13.2-13.7
*13.1
(
Display a grid
) Write a program that displays a grid, as shown in
Figure 13.26a. Use red color for vertical lines and blue for horizontals.
3
*
3
3
*
3
**13.2
(
Create a custom button class
) Develop a custom button class named
OvalButton
that extends
JButton
and displays the button text inside an oval.
Figure 13.26b shows two buttons created using the
OvalButton
class.
*13.3
(
Display a checkerboard
) Programming Exercise 12.10 displays a checkerboard
in which each white and black cell is a
JButton
. Rewrite a program that draws a
checkerboard on a
JPanel
using the drawing methods in the
Graphics
class, as
shown in Figure 13.26c. Use the
drawRect
method to draw each cell in the
checkerboard.
*13.4
(
Display a multiplication table
) Write a program that displays a multiplication
table in a panel using the drawing methods, as shown in Figure 13.27a.