Transcript Images

Images
26-Jul-16
Drawing images

Java can display .gif, .jpg (or .jpeg), and .png images


These are the only kinds it can display
Displaying them is (relatively) easy:


Get the Graphics of the panel you want to display them in
Call this method of your Graphics object:
boolean drawImage(Image img, int x, int y,
ImageObserver observer)
where:




img is the image
x, y are the coordinates of the upper left-hand corner
observer – the enclosing JFrame works well for this argument
Example:
myPanel.getGraphics().drawImage(myImage, 0, 0, this);
Why an ImageObserver?


boolean drawImage(Image img, int x, int y,
ImageObserver observer)
This method “Draws as much of the specified image as
is currently available.”



It returns true if the entire image is available
It notifies the ImageObserver if more has become available
In general, it would be nice if the images were loaded
before attempting to display them

In particular, attempting to display a null image is an error
Loading images

This is ridiculously difficult. Here goes...

Get a Toolkit that can load the image


Get a MediaTracker that can watch images being loaded



tracker.addImage(image, 0);
A MediaTracker can track any number of images at once
Tell the MediaTracker to start loading the images (bet you thought
getImage did this!) and wait for them to finish loading


Image image = toolkit.getImage(fileName);
Tell the MediaTracker to track the image


MediaTracker tracker = new MediaTracker(owner);
 A JFrame makes a perfectly good owner
Tell the toolkit that you want to load the image


Toolkit toolkit = Toolkit.getDefaultToolkit();
tracker.waitForAll();
Finally, handle the Exceptions that might occur
The End