Java Reference
In-Depth Information
Now consider the code in the applet below. This is very similar to the code above,
but declares an Image reference called image (changing the name of the ImageIcon
object to icon ) and replaces the line
image = new ImageIcon(getDocumentBase(), "earth.gif");
with the following two lines:
image = getImage(getDocumentBase(), "earth.gif");
icon = new ImageIcon(image);
Thus, instead of the call to getDocumentBase being within the constructor for the
ImageIcon object, it is used by method getImage to return an Image object. The
reference to this object is then used to construct an ImageIcon for the image.
Essentially, the only difference is that it is now getImage that is making the call to
getDocumentBase , rather than the ImageIcon constructor.
import java.awt.*;
import javax.swing.*;
import java.net.*;
public class ImageTest2b extends JApplet
{
private Image image;
private ImageIcon icon;
public void init()
{
image = getImage(getDocumentBase(), "earth.gif");
icon = new ImageIcon(image);
}
public void paint(Graphics g)
{
icon.paintIcon(this,g,0,0);
}
}
Though the changes would appear to be little more than superfi cial, the new
applet works fl awlessly under the appletviewer, Chrome and IE9! The output from
IE9 is shown in Fig. 12.13 .
It might be concluded from the above results that only class Image should be
used for handling images in applets, but this is not so. There are occasions when
only ImageIcon s will do the job. For example, ImageIcon s can be used in the
constructors for JLabel s and JButton s, but Image s cannot.
12.5
Scaling Images
An overloaded form of method drawImage takes six arguments, the two
Search WWH ::




Custom Search