KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > swing > ImageIcon


1 /*
2  * @(#)ImageIcon.java 1.53 03/12/19
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package javax.swing;
8
9 import java.awt.*;
10 import java.awt.image.*;
11 import java.net.URL JavaDoc;
12
13 import java.io.Serializable JavaDoc;
14 import java.io.ObjectOutputStream JavaDoc;
15 import java.io.ObjectInputStream JavaDoc;
16 import java.io.IOException JavaDoc;
17
18 import java.util.Locale JavaDoc;
19 import javax.accessibility.*;
20
21
22 /**
23  * An implementation of the Icon interface that paints Icons
24  * from Images. Images that are created from a URL, filename or byte array
25  * are preloaded using MediaTracker to monitor the loaded state
26  * of the image.
27  *
28  * <p>
29  * For further information and examples of using image icons, see
30  * <a HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/icon.html">How to Use Icons</a>
31  * in <em>The Java Tutorial.</em>
32  *
33  * <p>
34  * <strong>Warning:</strong>
35  * Serialized objects of this class will not be compatible with
36  * future Swing releases. The current serialization support is
37  * appropriate for short term storage or RMI between applications running
38  * the same version of Swing. As of 1.4, support for long term storage
39  * of all JavaBeans<sup><font size="-2">TM</font></sup>
40  * has been added to the <code>java.beans</code> package.
41  * Please see {@link java.beans.XMLEncoder}.
42  *
43  * @version 1.53 12/19/03
44  * @author Jeff Dinkins
45  * @author Lynn Monsanto
46  */

47 public class ImageIcon implements Icon JavaDoc, Serializable JavaDoc, Accessible {
48     /* Keep references to the filename and location so that
49      * alternate persistence schemes have the option to archive
50      * images symbolically rather than including the image data
51      * in the archive.
52      */

53     transient private String JavaDoc filename;
54     transient private URL JavaDoc location;
55
56     transient Image image;
57     transient int loadStatus = 0;
58     ImageObserver imageObserver;
59     String JavaDoc description = null;
60
61     protected final static Component component = new Component() {};
62     protected final static MediaTracker tracker = new MediaTracker(component);
63
64     /**
65      * Id used in loading images from MediaTracker.
66      */

67     private static int mediaTrackerID;
68
69     int width = -1;
70     int height = -1;
71
72     /**
73      * Creates an ImageIcon from the specified file. The image will
74      * be preloaded by using MediaTracker to monitor the loading state
75      * of the image.
76      * @param filename the name of the file containing the image
77      * @param description a brief textual description of the image
78      * @see #ImageIcon(String)
79      */

80     public ImageIcon(String JavaDoc filename, String JavaDoc description) {
81     image = Toolkit.getDefaultToolkit().getImage(filename);
82         if (image == null) {
83             return;
84         }
85     this.filename = filename;
86         this.description = description;
87     loadImage(image);
88     }
89
90     /**
91      * Creates an ImageIcon from the specified file. The image will
92      * be preloaded by using MediaTracker to monitor the loading state
93      * of the image. The specified String can be a file name or a
94      * file path. When specifying a path, use the Internet-standard
95      * forward-slash ("/") as a separator.
96      * (The string is converted to an URL, so the forward-slash works
97      * on all systems.)
98      * For example, specify:
99      * <pre>
100      * new ImageIcon("images/myImage.gif") </pre>
101      * The description is initialized to the <code>filename</code> string.
102      *
103      * @param filename a String specifying a filename or path
104      * @see #getDescription
105      */

106     public ImageIcon (String JavaDoc filename) {
107         this(filename, filename);
108     }
109
110     /**
111      * Creates an ImageIcon from the specified URL. The image will
112      * be preloaded by using MediaTracker to monitor the loaded state
113      * of the image.
114      * @param location the URL for the image
115      * @param description a brief textual description of the image
116      * @see #ImageIcon(String)
117      */

118     public ImageIcon(URL JavaDoc location, String JavaDoc description) {
119     image = Toolkit.getDefaultToolkit().getImage(location);
120         if (image == null) {
121             return;
122         }
123     this.location = location;
124         this.description = description;
125     loadImage(image);
126     }
127
128     /**
129      * Creates an ImageIcon from the specified URL. The image will
130      * be preloaded by using MediaTracker to monitor the loaded state
131      * of the image.
132      * The icon's description is initialized to be
133      * a string representation of the URL.
134      * @param location the URL for the image
135      * @see #getDescription
136      */

137     public ImageIcon (URL JavaDoc location) {
138         this(location, location.toExternalForm());
139     }
140
141     /**
142      * Creates an ImageIcon from the image.
143      * @param image the image
144      * @param description a brief textual description of the image
145      */

146     public ImageIcon(Image image, String JavaDoc description) {
147         this(image);
148         this.description = description;
149     }
150
151     /**
152      * Creates an ImageIcon from an image object.
153      * If the image has a "comment" property that is a string,
154      * then the string is used as the description of this icon.
155      * @param image the image
156      * @see #getDescription
157      * @see java.awt.Image#getProperty
158      */

159     public ImageIcon (Image image) {
160     this.image = image;
161         Object JavaDoc o = image.getProperty("comment", imageObserver);
162         if (o instanceof String JavaDoc) {
163             description = (String JavaDoc) o;
164         }
165     loadImage(image);
166     }
167
168     /**
169      * Creates an ImageIcon from an array of bytes which were
170      * read from an image file containing a supported image format,
171      * such as GIF, JPEG, or (as of 1.3) PNG.
172      * Normally this array is created
173      * by reading an image using Class.getResourceAsStream(), but
174      * the byte array may also be statically stored in a class.
175      *
176      * @param imageData an array of pixels in an image format supported
177      * by the AWT Toolkit, such as GIF, JPEG, or (as of 1.3) PNG
178      * @param description a brief textual description of the image
179      * @see java.awt.Toolkit#createImage
180      */

181     public ImageIcon (byte[] imageData, String JavaDoc description) {
182     this.image = Toolkit.getDefaultToolkit().createImage(imageData);
183         if (image == null) {
184             return;
185         }
186         this.description = description;
187     loadImage(image);
188     }
189
190     /**
191      * Creates an ImageIcon from an array of bytes which were
192      * read from an image file containing a supported image format,
193      * such as GIF, JPEG, or (as of 1.3) PNG.
194      * Normally this array is created
195      * by reading an image using Class.getResourceAsStream(), but
196      * the byte array may also be statically stored in a class.
197      * If the resulting image has a "comment" property that is a string,
198      * then the string is used as the description of this icon.
199      *
200      * @param imageData an array of pixels in an image format supported by
201      * the AWT Toolkit, such as GIF, JPEG, or (as of 1.3) PNG
202      * @see java.awt.Toolkit#createImage
203      * @see #getDescription
204      * @see java.awt.Image#getProperty
205      */

206     public ImageIcon (byte[] imageData) {
207     this.image = Toolkit.getDefaultToolkit().createImage(imageData);
208         if (image == null) {
209             return;
210         }
211         Object JavaDoc o = image.getProperty("comment", imageObserver);
212         if (o instanceof String JavaDoc) {
213             description = (String JavaDoc) o;
214         }
215     loadImage(image);
216     }
217
218     /**
219      * Creates an uninitialized image icon.
220      */

221     public ImageIcon() {
222     }
223
224     /**
225      * Loads the image, returning only when the image is loaded.
226      * @param image the image
227      */

228     protected void loadImage(Image image) {
229     synchronized(tracker) {
230             int id = getNextID();
231
232         tracker.addImage(image, id);
233         try {
234         tracker.waitForID(id, 0);
235         } catch (InterruptedException JavaDoc e) {
236         System.out.println("INTERRUPTED while loading Image");
237         }
238             loadStatus = tracker.statusID(id, false);
239         tracker.removeImage(image, id);
240
241         width = image.getWidth(imageObserver);
242         height = image.getHeight(imageObserver);
243     }
244     }
245
246     /**
247      * Returns an ID to use with the MediaTracker in loading an image.
248      */

249     private int getNextID() {
250         synchronized(tracker) {
251             return ++mediaTrackerID;
252         }
253     }
254
255     /**
256      * Returns the status of the image loading operation.
257      * @return the loading status as defined by java.awt.MediaTracker
258      * @see java.awt.MediaTracker#ABORTED
259      * @see java.awt.MediaTracker#ERRORED
260      * @see java.awt.MediaTracker#COMPLETE
261      */

262     public int getImageLoadStatus() {
263         return loadStatus;
264     }
265
266     /**
267      * Returns this icon's <code>Image</code>.
268      * @return the <code>Image</code> object for this <code>ImageIcon</code>
269      */

270     public Image getImage() {
271     return image;
272     }
273
274     /**
275      * Sets the image displayed by this icon.
276      * @param image the image
277      */

278     public void setImage(Image image) {
279     this.image = image;
280     loadImage(image);
281     }
282
283     /**
284      * Gets the description of the image. This is meant to be a brief
285      * textual description of the object. For example, it might be
286      * presented to a blind user to give an indication of the purpose
287      * of the image.
288      * The description may be null.
289      *
290      * @return a brief textual description of the image
291      */

292     public String JavaDoc getDescription() {
293     return description;
294     }
295
296     /**
297      * Sets the description of the image. This is meant to be a brief
298      * textual description of the object. For example, it might be
299      * presented to a blind user to give an indication of the purpose
300      * of the image.
301      * @param description a brief textual description of the image
302      */

303     public void setDescription(String JavaDoc description) {
304     this.description = description;
305     }
306
307     /**
308      * Paints the icon.
309      * The top-left corner of the icon is drawn at
310      * the point (<code>x</code>, <code>y</code>)
311      * in the coordinate space of the graphics context <code>g</code>.
312      * If this icon has no image observer,
313      * this method uses the <code>c</code> component
314      * as the observer.
315      *
316      * @param c the component to be used as the observer
317      * if this icon has no image observer
318      * @param g the graphics context
319      * @param x the X coordinate of the icon's top-left corner
320      * @param y the Y coordinate of the icon's top-left corner
321      */

322     public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
323         if(imageObserver == null) {
324            g.drawImage(image, x, y, c);
325         } else {
326        g.drawImage(image, x, y, imageObserver);
327         }
328     }
329
330     /**
331      * Gets the width of the icon.
332      *
333      * @return the width in pixels of this icon
334      */

335     public int getIconWidth() {
336     return width;
337     }
338
339     /**
340      * Gets the height of the icon.
341      *
342      * @return the height in pixels of this icon
343      */

344     public int getIconHeight() {
345     return height;
346     }
347
348     /**
349      * Sets the image observer for the image. Set this
350      * property if the ImageIcon contains an animated GIF, so
351      * the observer is notified to update its display.
352      * For example:
353      * <pre>
354      * icon = new ImageIcon(...)
355      * button.setIcon(icon);
356      * icon.setImageObserver(button);
357      * </pre>
358      *
359      * @param observer the image observer
360      */

361     public void setImageObserver(ImageObserver observer) {
362         imageObserver = observer;
363     }
364
365     /**
366      * Returns the image observer for the image.
367      *
368      * @return the image observer, which may be null
369      */

370     public ImageObserver getImageObserver() {
371         return imageObserver;
372     }
373
374     /**
375      * Returns a string representation of this image.
376      *
377      * @return a string representing this image
378      */

379     public String JavaDoc toString() {
380         if (description != null) {
381             return description;
382         }
383         return super.toString();
384     }
385
386     private void readObject(ObjectInputStream JavaDoc s)
387     throws ClassNotFoundException JavaDoc, IOException JavaDoc
388     {
389     s.defaultReadObject();
390     
391     int w = s.readInt();
392     int h = s.readInt();
393     int[] pixels = (int[])(s.readObject());
394
395         if (pixels != null) {
396         Toolkit tk = Toolkit.getDefaultToolkit();
397         ColorModel cm = ColorModel.getRGBdefault();
398         image = tk.createImage(new MemoryImageSource(w, h, cm, pixels, 0, w));
399         loadImage(image);
400         }
401     }
402
403
404     private void writeObject(ObjectOutputStream JavaDoc s)
405     throws IOException JavaDoc
406     {
407     s.defaultWriteObject();
408
409     int w = getIconWidth();
410     int h = getIconHeight();
411     int[] pixels = image != null? new int[w * h] : null;
412
413         if (image != null) {
414         try {
415             PixelGrabber pg = new PixelGrabber(image, 0, 0, w, h, pixels, 0, w);
416             pg.grabPixels();
417             if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
418             throw new IOException JavaDoc("failed to load image contents");
419             }
420         }
421         catch (InterruptedException JavaDoc e) {
422             throw new IOException JavaDoc("image load interrupted");
423         }
424         }
425     
426     s.writeInt(w);
427     s.writeInt(h);
428     s.writeObject(pixels);
429     }
430
431     /**
432      * --- Accessibility Support ---
433      */

434
435     private AccessibleImageIcon accessibleContext = null;
436
437     /**
438      * Gets the AccessibleContext associated with this ImageIcon.
439      * For image icons, the AccessibleContext takes the form of an
440      * AccessibleImageIcon.
441      * A new AccessibleImageIcon instance is created if necessary.
442      *
443      * @return an AccessibleImageIcon that serves as the
444      * AccessibleContext of this ImageIcon
445      * @beaninfo
446      * expert: true
447      * description: The AccessibleContext associated with this ImageIcon.
448      */

449     public AccessibleContext getAccessibleContext() {
450         if (accessibleContext == null) {
451             accessibleContext = new AccessibleImageIcon();
452         }
453         return accessibleContext;
454     }
455
456     /**
457      * This class implements accessibility support for the
458      * <code>ImageIcon</code> class. It provides an implementation of the
459      * Java Accessibility API appropriate to image icon user-interface
460      * elements.
461      * <p>
462      * <strong>Warning:</strong>
463      * Serialized objects of this class will not be compatible with
464      * future Swing releases. The current serialization support is
465      * appropriate for short term storage or RMI between applications running
466      * the same version of Swing. As of 1.4, support for long term storage
467      * of all JavaBeans<sup><font size="-2">TM</font></sup>
468      * has been added to the <code>java.beans</code> package.
469      * Please see {@link java.beans.XMLEncoder}.
470      */

471     protected class AccessibleImageIcon extends AccessibleContext
472         implements AccessibleIcon, Serializable JavaDoc {
473
474     /*
475      * AccessibleContest implementation -----------------
476      */

477
478         /**
479          * Gets the role of this object.
480          *
481          * @return an instance of AccessibleRole describing the role of the
482          * object
483          * @see AccessibleRole
484          */

485         public AccessibleRole getAccessibleRole() {
486             return AccessibleRole.ICON;
487         }
488
489         /**
490          * Gets the state of this object.
491          *
492          * @return an instance of AccessibleStateSet containing the current
493          * state set of the object
494          * @see AccessibleState
495          */

496         public AccessibleStateSet getAccessibleStateSet() {
497             return null;
498         }
499
500         /**
501          * Gets the Accessible parent of this object. If the parent of this
502          * object implements Accessible, this method should simply return
503          * getParent().
504          *
505          * @return the Accessible parent of this object -- can be null if this
506          * object does not have an Accessible parent
507          */

508         public Accessible getAccessibleParent() {
509             return null;
510         }
511
512         /**
513          * Gets the index of this object in its accessible parent.
514          *
515          * @return the index of this object in its parent; -1 if this
516          * object does not have an accessible parent.
517          * @see #getAccessibleParent
518          */

519         public int getAccessibleIndexInParent() {
520             return -1;
521         }
522
523         /**
524          * Returns the number of accessible children in the object. If all
525          * of the children of this object implement Accessible, than this
526          * method should return the number of children of this object.
527          *
528          * @return the number of accessible children in the object.
529          */

530         public int getAccessibleChildrenCount() {
531         return 0;
532         }
533
534         /**
535          * Returns the nth Accessible child of the object.
536          *
537          * @param i zero-based index of child
538          * @return the nth Accessible child of the object
539          */

540         public Accessible getAccessibleChild(int i) {
541         return null;
542         }
543
544         /**
545          * Returns the locale of this object.
546          *
547          * @return the locale of this object
548          */

549     public Locale JavaDoc getLocale() throws IllegalComponentStateException {
550             return null;
551         }
552     
553     /*
554      * AccessibleIcon implementation -----------------
555      */

556
557     /**
558      * Gets the description of the icon. This is meant to be a brief
559      * textual description of the object. For example, it might be
560      * presented to a blind user to give an indication of the purpose
561      * of the icon.
562      *
563      * @return the description of the icon
564      */

565     public String JavaDoc getAccessibleIconDescription() {
566         return ImageIcon.this.getDescription();
567     }
568     
569     /**
570      * Sets the description of the icon. This is meant to be a brief
571      * textual description of the object. For example, it might be
572      * presented to a blind user to give an indication of the purpose
573      * of the icon.
574      *
575      * @param description the description of the icon
576      */

577     public void setAccessibleIconDescription(String JavaDoc description) {
578         ImageIcon.this.setDescription(description);
579     }
580     
581     /**
582      * Gets the height of the icon.
583      *
584      * @return the height of the icon
585      */

586     public int getAccessibleIconHeight() {
587         return ImageIcon.this.height;
588     }
589
590     /**
591      * Gets the width of the icon.
592      *
593      * @return the width of the icon
594      */

595     public int getAccessibleIconWidth() {
596         return ImageIcon.this.width;
597     }
598
599         private void readObject(ObjectInputStream JavaDoc s)
600         throws ClassNotFoundException JavaDoc, IOException JavaDoc
601         {
602         s.defaultReadObject();
603     }
604
605         private void writeObject(ObjectOutputStream JavaDoc s)
606         throws IOException JavaDoc
607         {
608         s.defaultWriteObject();
609         }
610     } // AccessibleImageIcon
611
}
612
613
Popular Tags