Java Reference
In-Depth Information
Solution
Use the Graphics drawImage() method in your paint routine. Image objects represent bit-
maps. They are normally loaded from a file via getImage() but can also be synthesized us-
ing createImage() . You can't construct them yourself, however: the Image class is abstract.
Once you have an image, displaying it is trivial:
// File graphics/DrawImageDemo.java
public void paint(Graphics g) {
g.drawImage(0, 0, myImage, this);
}
Discussion
You can get an image by using a routine named, naturally, getImage() . If your code is used
only in an applet, you can use the Applet method getImage() , but if you want it to run in an
application as well, you need to use the Toolkit version, which takes either a filename or a
URL. The filename, of course, when it turns up in an applet, fails with a security exception
unless the user installs a policy file. Program GetImage shows the code for doing this both
ways:
public
public class
class GetImage
GetImage extends
extends JApplet {
private
private static
static final
final long
long serialVersionUID = 4288395022095915666L ;
private
private Image image ;
public
public void
void init () {
loadImage ();
}
public
public void
void loadImage () {
// Portable version: getClass().getResource() works in either
// applet or application, 1.1 or 1.3, returns URL for file name.
URL url = getClass (). getResource ( "Duke.gif" );
image = getToolkit (). getImage ( url );
// Or just:
// image = getToolkit().getImage(getClass().getResource("Duke.gif"));
}
@Override
Search WWH ::




Custom Search