1 19 20 package com.sshtools.ui.swing; 21 22 import java.net.URL ; 23 import java.util.HashMap ; 24 import java.awt.Image ; 25 import java.awt.Toolkit ; 26 import javax.swing.ImageIcon ; 27 28 34 public class ResourceIcon extends ImageIcon { 35 private Class cls; 37 38 private HashMap imageCache = new HashMap (); 39 40 public ResourceIcon(String image) { 41 super(); 42 init(getClass(), image); 43 } 44 45 52 public ResourceIcon(Class cls, String image) { 53 super(); 54 init(cls, image); 55 } 56 57 public ResourceIcon(URL iconResource) { 58 super(iconResource); 59 } 60 61 public void init(Class cls, String image) { 62 this.cls = cls; 63 if (image.startsWith("/")) { loadImage(image); 65 } else { 66 int idx = cls.getName().lastIndexOf('.'); 67 String packageName = idx == -1 ? null : cls.getName().substring(0, idx); 68 String path = packageName == null ? "" : "/" + packageName; path = path.replace('.', '/'); 70 path += ("/" + image); loadImage(path); 72 } 73 } 74 75 protected void loadImage(String imageName) { 76 Image image = (Image ) imageCache.get(imageName); 77 if (image == null) { 78 URL url = cls.getResource(imageName); 79 if (url != null) { 80 image = Toolkit.getDefaultToolkit().getImage(url); 81 } else { 82 url = cls.getClassLoader().getResource(imageName); 83 if (url != null) { 84 image = Toolkit.getDefaultToolkit().getImage(url); 85 } else { 86 image = Toolkit.getDefaultToolkit().getImage(imageName); 87 } 88 } 89 imageCache.put(imageName, image); 90 } 91 if (image != null) { 92 this.setImage(image); 93 } else { 94 System.err.println(Messages.getString("ResourceIcon.nullImage")); } 96 } 97 } 98 | Popular Tags |