Source code: org/altara/util/IconService.java
1 /* Altara Utility Classes
2 Copyright (c) 2001,2002 Brian H. Trammell
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with this library; if not, it is available at
16 http://www.gnu.org/copyleft/lesser.html, or by writing to the
17 Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 Boston, MA 02111-1307 USA
19 */
20
21 package org.altara.util;
22
23 import java.net.*;
24 import java.util.*;
25 import java.awt.*;
26 import java.awt.image.*;
27 import javax.swing.*;
28
29 public class IconService {
30
31 String iconPath;
32 Class classBase;
33 Map iconCache;
34 static IconService current;
35
36 private IconService (Class classBase, String iconPath) {
37 this.classBase = classBase;
38 this.iconPath = iconPath;
39 this.iconCache = new HashMap();
40 current = this;
41 }
42
43 public static void initialize(Class classBase, String iconPath) {
44 new IconService(classBase, iconPath);
45 }
46
47 public static ImageIcon getIcon(String iconName) {
48 try {
49 return current.getIconImpl(iconName);
50 } catch (NullPointerException ex) {
51 throw new IconServiceNotInitializedException();
52 }
53 }
54
55 private synchronized ImageIcon getIconImpl(String iconName) {
56 // Try the cache first
57 ImageIcon icon;
58 icon = (ImageIcon)iconCache.get(iconName);
59 if (icon == null) {
60 // cache miss - load icon
61 URL iconUrl =
62 classBase.getResource(iconPath+"/"+iconName);
63 if (iconUrl == null) {
64 throw new IconNotFoundException(iconName);
65 }
66 icon = new ImageIcon(iconUrl);
67 iconCache.put(iconName,icon);
68 }
69 return icon;
70 }
71
72 public static class IconNotFoundException
73 extends IconServiceException {
74 IconNotFoundException(String msg) {
75 super(msg);
76 }
77 }
78
79 public static class IconServiceNotInitializedException
80 extends IconServiceException {
81 IconServiceNotInitializedException() {
82 super("Attempt to call getIcon() before initialize()");
83 }
84 }
85
86 public static class IconServiceException extends RuntimeException {
87 IconServiceException(String msg) {
88 super(msg);
89 }
90 }
91 }