KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtriver > open > vectorvisuals > ImageManager


1 /*
2  * ImageManager.java
3  *
4  * Created on 2 June 2003, 13:13
5  */

6
7 package com.thoughtriver.open.vectorvisuals;
8
9 import java.awt.*;
10 import java.net.*;
11 import java.util.*;
12
13 import javax.swing.*;
14
15 /**
16  * This is a simple utility to assist in the quick use of <CODE>Image</CODE>
17  * objects. Each instance of <CODE>ImageManager</CODE> maintains a cache of
18  * loaded images that is populated as the images are requested with the <CODE>getImage</CODE>
19  * method.
20  *
21  * @author Brandon Franklin
22  * @version $Date: 2006/11/25 09:18:36 $
23  */

24 public class ImageManager {
25
26     /** The singleton instance of <CODE>ImageManager</CODE> */
27     static private ImageManager singleton = null;
28
29     /**
30      * Returns the shared instance of <CODE>ImageManager</CODE>, which is
31      * useful if a unified <CODE>Image</CODE> cache is desired.
32      *
33      * @return the <CODE>ImageManager</CODE> singleton
34      */

35     static synchronized public ImageManager getSharedInstance() {
36
37         if (singleton == null) {
38             singleton = new ImageManager();
39         }
40
41         return singleton;
42     }
43
44     /** A name-to-<CODE>Image</CODE> record of all loaded images */
45     private Map<String JavaDoc, Image> cache = null;
46
47     /**
48      * Creates a new instance of <CODE>ImageManager</CODE> and prepares it for
49      * use.
50      */

51     public ImageManager() {
52         cache = new HashMap<String JavaDoc, Image>();
53     }
54
55     /**
56      * Retrieves and returns the <CODE>Image</CODE> with the supplied name.
57      * This will involve either loading the image from an external resource or
58      * returning it directly from the <CODE>ImageManager</CODE>'s cache.
59      *
60      * @param name the name of the image to retrieve
61      * @return the <CODE>Image</CODE> requested
62      */

63     public synchronized Image getImage(final String JavaDoc name) {
64
65         Image img = null;
66
67         // First check the cache
68
if (cache.containsKey(name)) {
69             img = cache.get(name);
70
71         }
72         else { // Not in the cache, so try loading it
73

74             URL imgLoc = Thread.currentThread().getContextClassLoader().getResource(name);
75             img = new ImageIcon(imgLoc).getImage();
76
77             // Store the image in the cache
78
if (img != null) {
79                 cache.put(name, img);
80             }
81         }
82
83         return img;
84     }
85
86 }
87
Popular Tags