The first version returns an Image object that encapsulates the image found at the location
specified by url. The second version returns an Image object that encapsulates the image
found at the location specified by url and having the name specified by imageName.
Displaying an Image
Once you have an image, you can display it by using drawImage( ), which is a member of
the Graphics class. It has several forms. The one we will be using is shown here:
boolean drawImage(Image imgObj, int left, int top, ImageObserver imgOb)
This displays the image passed in imgObj with its upper-left corner specified by left and top.
imgOb is a reference to a class that implements the ImageObserver interface. This interface
is implemented by all AWT components. An image observer is an object that can monitor an
image while it loads. ImageObserver is described in the next section.
With getImage( ) and drawImage( ), it is actually quite easy to load and display an
image. Here is a sample applet that loads and displays a single image. The file seattle.jpg is
loaded, but you can substitute any GIF, JPG, or PNG file you like (just make sure it is
available in the same directory with the HTML file that contains the applet).
/*
* <applet code="SimpleImageLoad" width=248 height=146>
*  <param name="img" value="seattle.jpg">
* </applet>
*/
import java.awt.*;
import java.applet.*;
public class SimpleImageLoad extends Applet
{
Image img;
public void init() {
img = getImage(getDocumentBase(), getParameter("img"));
}
public void paint(Graphics g) {
g.drawImage(img, 0, 0, this);
}
}
In the init( ) method, the img variable is assigned to the image returned by
getImage( ). The getImage( ) method uses the string returned by getParameter("img")
as the filename for the image. This image is loaded from a URL that is relative to the
result of getDocumentBase( ), which is the URL of the HTML page this applet tag was in.
The filename returned by getParameter("img") comes from the applet tag <param name=
"img" value="seattle.jpg">. This is the equivalent, if a little slower, of using the HTML
tag <img src="seattle.jpg" width=248 height=146>. Figure 25-1 shows what it looks like
when you run the program.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home