swt通过扩展名取系统图标,swt扩展名取图标,eclipse swt可
分享于 点击 6765 次 点评:217
swt通过扩展名取系统图标,swt扩展名取图标,eclipse swt可
eclipse swt可以通过扩展名取得Program,从而取得系统图标,必须注意的是,在Linux平台下是扩展名是分大小写的,这里统一转化为小写处理即可。参考代码如下:
package cn.outofmemory.test.resource;import java.util.Enumeration;import java.util.Hashtable;import java.util.logging.Logger;import org.eclipse.jface.resource.ImageDescriptor;import org.eclipse.swt.SWT;import org.eclipse.swt.graphics.Image;import org.eclipse.swt.graphics.ImageData;import org.eclipse.swt.program.Program;/** * 图像工厂 * * @author Leo * */public class ImageFactory { private static final Logger LOG = Logger.getLogger(ImageFactory.class.getName()); public static final String UNKNOWN_FILE = "unknown.png"; public static final String DLL_FILE = "dll.png"; private static Hashtable<String, Image> images = new Hashtable<String, Image>(); private ImageFactory() { } /** * 销毁工厂 */ public static void dispose() { Enumeration<Image> e = images.elements(); while (e.hasMoreElements()) { Image image = e.nextElement(); if (!image.isDisposed()) { image.dispose(); } } images.clear(); } /** * 取文件的系统图标 * * @param fileName * 文件名 * @return 文件的系统图标 */ public static Image getSystemIconImage(String fileName) { if (fileName == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } Image iconImage = null; int dot = fileName.lastIndexOf('.'); if (dot != -1) {// 有扩展名 String extension = fileName.substring(dot).toLowerCase();//linux下分大小 写 iconImage = images.get(extension);//缓存 if (iconImage == null) { iconImage = loadProgramImage(extension); } if (iconImage == null) {// 无系统关联图标 LOG.info("无系统关联图标:"+fileName); iconImage = loadDefined(extension); } } else {// 无扩展名 iconImage = loadImage(UNKNOWN_FILE); } return iconImage; } /** * 加载预定义图标 * @param extension 文件扩展名 * @return 预定义图标,或未知图标 */ private static Image loadDefined(String extension) { Image iconImage; if (".dll".equals(extension)) { iconImage = loadImage(DLL_FILE); } else { iconImage = loadImage(UNKNOWN_FILE); } images.put(extension, iconImage); return iconImage; } /** * 加载关联图标 * @param extension 文件扩展名 * @return 文件的关联图标,或为 null */ private static Image loadProgramImage(String extension) { Image iconImage = null; Program program = Program.findProgram(extension); if (program != null) { ImageData imageData = program.getImageData(); if (imageData != null) { iconImage = new Image(null, imageData, imageData.getTransparencyMask()); images.put(extension, iconImage); } } return iconImage; }}
用户点评