Java Reference
In-Depth Information
image.Forthisreason,Javaprovidesthe
java.awt.image.ImageObserver
in-
terface to provide the current image-loading status.
Note
ImageObserver
letsyouobtaininformationaboutaloadedimageassoon
asit'savailablewhiletheimageisbeingconstructed,byprovidinga
boolean im-
ageUpdate(Image img, int infoflags, int x, int y, int
width, int height)
method that's called at various times during the load-
ing process.
infoflags
consists of various
ImageObserver
constants (such as
SOMEBITS
and
ERROR
)thathavebeencombinedviathebitwiseinclusiveORoperat-
or.Theotherargumentsdependupon
infoflags
.Forexample,when
infoflags
is set to
SOMEBITS
, they define a bounding box for the newly loaded pixels.
Various
Image
and
Graphics
methodsaredeclaredwith
ImageObserver
para-
meters. For example,
Image
's
int getWidth(ImageObserver observer)
and
int getHeight(ImageObserver observer)
methodsarecalledwithan
image observer that helps these methods determine that the image has been loaded to
the point where they can return its width or height, or that the width/height is still not
available, in which case they return -1.
Similarly,the
Graphics
class's
boolean drawImage(Image img, int x,
int y, ImageObserver observer)
methodiscalledwithanimageobserver
thathelpsitdeterminewhatpartoftheimagetodraw—theimage'supper-leftcorneris
locatedat(
x
,
y
).Whenanimageisnotcompletelyloaded,theimageobservercallsone
of
Component
's
repaint()
methods, to reinvoke
paint()
so that a subsequent
call can be made to
drawImage()
to draw the newly-loaded pixels.
Note
You do not need to implement
ImageObserver
(unless there is a special
reason to do so) because
Component
already implements this interface on your be-
half.
I've created an
ImageViewer
application that shows you how to load and display
animage.Thisapplicationconsistsof
ImageViewer
and
ImageCanvas
classes,and
Listing 7-4
. A general-purpose image viewer
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FileDialog;
import java.awt.Frame;