轉(zhuǎn)自:http://blog.csdn.net/moneyice/archive/2006/04/25/677423.aspx
每個(gè)UI程序都離不開圖片,一般的Eclipse插件,在一個(gè)類中定義了若干靜態(tài)常量,每一個(gè)常量指定一個(gè)icon的名字,在程序中用到圖片的時(shí)候,通過這個(gè)常量計(jì)算得到圖片。Eclipse的插件一般規(guī)模較大,圖片很多,而且分不同的像素,彩色,灰白等。這樣有利于統(tǒng)一的管理和開發(fā)人員的溝通。
但并不是每個(gè)plugin或者rcp都要用到這么多圖片,如果只有很少的圖片的話,可以用圖片的名字作為key,來存取圖片。程序例子如下:
public class ImageShop {
private static ImageRegistry register = new ImageRegistry();
private static Set keys = new HashSet();
static {
initial();
}
public static ImageDescriptor getDescriptor(String key) {
ImageDescriptor image = register.getDescriptor(key);
if (image == null) {
image = ImageDescriptor.getMissingImageDescriptor();
}
return image;
}
public static Image get(String key) {
Image image = register.get(key);
if (image == null) {
image = ImageDescriptor.getMissingImageDescriptor().createImage();
}
return image;
}
public static String[] getImageKey() {
return (String[]) keys.toArray(new String[keys.size()]);
}
private static void initial() {
Bundle bundle = Platform.getBundle(PwdgatePlugin.ID);
URL url = bundle.getEntry("icons");
try {
url = Platform.asLocalURL(url);
} catch (Exception e) {
PwdgatePlugin.log("get root path", e);
}
File file = new File(url.getPath());
File[] images = file.listFiles();
for (int i = 0; i < images.length; i++) {
File f = images[i];
if (!f.isFile()) {
continue;
}
String name = f.getName();
if (!name.endsWith(".gif")) {
continue;
}
String key = name.substring(0, name.indexOf('.'));
URL fullPathString = bundle.getEntry("icons/" + name);
ImageDescriptor des = ImageDescriptor.createFromURL(fullPathString);
register.put(key, des);
keys.add(key);
}
}
}
所有的圖片都放在根目錄/icons目錄下,在系統(tǒng)中如果用到名字為default.gif的圖片,只要調(diào)用ImageShop.get(“default”)即可;有時(shí)在Action中需要用到ImageDescriptor,調(diào)用ImageShop. getDescriptor(“default”)就可以取到。