Swing provides a concrete implementation of the Icon interface that is considerably more useful than our OvalIcon class. ImageIcon uses a java.awt.Image object to store and display any graphic and provides synchronous image loading (i.e., the Image is loaded completely before returning), making ImageIcons very powerful and easy to use. You can even use an ImageIcon to display an animated GIF89a, making the ubiquitous "animation applet" as simple as this: // AnimationApplet.java // import javax.swing.*; // A simple animation applet public class AnimationApplet extends JApplet { public void init( ) { ImageIcon icon = new ImageIcon("images/rolling.gif"); // Animated gif getContentPane( ).add(new JLabel(icon)); } } All we did here was load an animated GIF in the init( ) method and then add it to the applet. For more information on JApplet, see Chapter 8. ImageIcon currently supports the JPEG, GIF (including animation and transparency), PNG, and XBM image formats. TIFF support should be coming soon. SVG might be supported eventually. 4.7.1 PropertiesThe ImageIcon class defines the properties listed in Table 4-4. The description property allows an arbitrary description of the image to be specified. One possible use of this property might be to give a blind user an audio description of the image.
The iconHeight and iconWidth properties default to -1 if no image is loaded by the constructor, while the image property simply contains the Image object rendered by the icon. ImageLoadStatus indicates the success or failure of the image load process using the constants defined in java.awt.MediaTracker (ABORTED, ERRORED, or COMPLETE). The default for this property is 0, which does not map to any of these constants. The imageObserver property contains the ImageObserver that should receive notifications of changes to the image. If this property is null (as it is by default), the component containing the icon will be treated as the image observer when the image is painted. Figure 4-9 shows a class diagram for ImageIcon and the classes related to it. Figure 4-9. ImageIcon class diagram4.7.2 SerializationLike most Swing classes, ImageIcon implements Serializable. The keen observer may see a problem with this: the java.awt.Image class used by ImageIcon is not serializable. By default, this would keep ImageIcon objects from serializing properly. The good news is that ImageIcon implements its own readObject( ) and writeObject( ) methods so that the pixel representation of the image is stored and retrieved correctly. 4.7.3 Constructors
4.7.4 User Interface Method
|