getImage() drawImage() Example
Java gets an image for an applet in a thread which allows the applet's execution to continue. By placing the call to getImage() in the init() method, which only runs once (unlike start() which runs each time the page using the applet is displayed), it can then be drawn in different places and resized without the need for it to be downloaded again. The image is the flag of Hong Kong and it is drawn three times in different parts opf the applet's drawing area, and with different sizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// getImage() drawImage() Example
import java.awt.*;
import javax.swing.*;
import java.io.*;
class GetImageDrawImageExample extends JApplet {
private Image im;
@Override public void init() {
im = getImage(getDocumentBase(), "images/HK.gif");
}
@Override public void paint(Graphics g) {
super.paint(g);
int w = im.getWidth(null);
int h = im.getHeight(null);
g.drawImage(im, (300-w)/2, (300-h)/2, this); // centered
g.drawImage(im, 0, 0, this); // new origin
g.drawImage(im, 200, 200, w/2, h/2, this); // size change
}
}
10 The method getImage() uses the URL of the document containing the applet, and the file name of the image, to downLoad the image.
15-16 The methods Image.getWidth() and Image.getHeight() have a null parameter. For larger images it is advisable to have an ImageObserver as parameter to enable an image's width and height to be determined reliably.
17-19 Some of the overloaded methods available for Graphics.drawImage() are:
drawImage(image, x, y, imageObserver) drawImage(image, x, y, bgColor, imageObserver) drawImage(image, x, y, width, height, imageObserver) drawImage(image, x, y, width, height, bgColor, imageObserver)
