Java Reference
In-Depth Information
+
x
(0, 0)
x
-axis
(
x
,
y
)
+
y
y
-axis
Fig. 13.2
|
Java coordinate system. Units are measured in pixels.
A
graphics context
enables drawing on the screen. A
Graphics
object manages a graphics
context and draws pixels on the screen that represent
text
and other graphical objects (e.g.,
lines
,
ellipses
,
rectangles
and other
polygons
).
Graphics
objects contain methods for
drawing
,
font manipulation
,
color manipulation
and the like.
Class
Graphics
is an
abstract
class (i.e., you cannot instantiate
Graphics
objects).
This contributes to Java's portability. Because drawing is performed
differently
on every
platform that supports Java, there cannot be only one implementation of the drawing
capabilities across all systems. When Java is implemented on a particular platform, a sub-
class of
Graphics
is created that implements the drawing capabilities. This implementa-
tion is hidden by class
Graphics
, which supplies the interface that enables us to use
graphics in a
platform-independent
manner.
Recall from Chapter 12 that class
Component
is the
superclass
for many of the classes
in package
java.awt
. Class
JComponent
(package
javax.swing
), which inherits indirectly
from class
Component
, contains a
paintComponent
method that can be used to draw
graphics. Method
paintComponent
takes a
Graphics
object as an argument. This object is
passed to the
paintComponent
method by the system when a lightweight Swing compo-
nent needs to be repainted. The header for the
paintComponent
method is
public void
paintComponent(Graphics g)
Parameter
g
receives a reference to an instance of the system-specific subclass of
Graphics
.
The preceding method header should look familiar to you—it's the same one we used in
some of the applications in Chapter 12. Actually, class
JComponent
is a
superclass
of
JPan-
el
. Many capabilities of class
JPanel
are inherited from class
JComponent
.
You seldom call method
paintComponent
directly, because drawing graphics is an
event-driven
process. As we mentioned in Chapter 11, Java uses a
multithreaded
model of
program execution. Each thread is a
parallel
activity. Each program can have many threads.
When you create a GUI-based application, one of those threads is known as the
event-
dispatch thread (EDT)
—it's used to process all GUI events. All manipulation of the on-
screen GUI components must be performed in that thread. When a GUI application exe-
cutes, the application container calls method
paintComponent
(in the event-dispatch
thread) for each lightweight component as the GUI is displayed. For
paintComponent
to
be called again, an event must occur (such as
covering
and
uncovering
the component with
another window).