Java Reference
In-Depth Information
tainer
classes.
Images
AWT supports GIF, JPEG, and PNG images via
java.awt.Image
,
Toolkit
, and
other classes. Because Java 2D largely obviates the need to work with these classes,
I won't discuss AWT's support for images in great detail. However, you should know
something about this support because various JFC classes (such as
javax.swing.ImageIcon
)workwith
Image
,andevenprovideconstructorsand/
or methods that take
Image
arguments and (in regard to methods) return
Image
in-
stances.
The
Toolkit
class declares several
createImage()
methods for creating and
returning
Image
objects from various sources. For example,
Image cre-
ateImage(String filename)
returnsan
Image
objectthatrepresentstheimage
defined in the file identified by
filename
.
Toolkit
also declares two
getImage()
methods that create and return
Image
objects. Unlike their
createImage()
counterparts, the
getImage()
methods
cache
Image
objects and can return the same object to different callers. This sharing
mechanism helps AWT save heap space, especially when large images are loaded. In
contrast,the
createImage()
methodsalwaysreturnnew
Image
objectsthatarenot
shared among callers.
Image
objects represent images but do not contain them: a loaded image is asso-
ciated with an
Image
object. This dichotomy exists because Java was originally used
mainly in a web browser context.
At that time, computers and network connections were much slower than they are
today, and loading large images over the wire was a time-consuming process. Rather
thanforcean
applet
(abrowser-basedapplication)towaituntilanimagehadcompletely
loaded(andannoytheuser),itwasdecidedthatmethodsforloadingimageswouldload
themasynchronouslyviabackgroundthreadswhileoccupyingtheuser'sattentionelse-
where.
When you invoke a
createImage()
or
getImage()
method, a background
thread is started to load the image, and
createImage()
/
getImage()
returns im-
mediately with an
Image
object.
Becausetheimagemaynotbefullyloadeduntilsometimeafterthemethodreturns,
you cannot immediately obtain the image's width and height, or even draw the entire