`

SWT中org.eclipse.swt.SWTError: No more handles

 
阅读更多
在RCP开发中如果牵涉到 Color,Image,Font,Cursor 等的过频的操作或者数据量比较大时  出现该异常的可能性就很大了。

由于这些类的对象 每new一个就要消耗掉一个handler ,如果没有及时的dispose,而系统分配的handler数量有限,于是出现了该错误。

============

解决办法就是用缓存,在java里面可以用Map集合的形式来处理,把用到了每一个对象分别放到对应的Map中,在不需要时,对其dispose同时clear Map集合。

==================

缓存文件结构大概如下:

public class CacheManager {
 //  colorMap
 public static Map<RGB, Color> colorMap = new HashMap<RGB, Color>();

 public static Color getColor(int systemColorID) {
  Display display = Display.getCurrent();
  return display.getSystemColor(systemColorID);
 }

 
 public static Color getColor(int r, int g, int b) {
  return getColor(new RGB(r, g, b));
 }

 public static Color getColor(RGB rgb) {
  Color color = colorMap.get(rgb);
  if (color == null) {
   Display display = Display.getCurrent();
   color = new Color(display, rgb);
   colorMap.put(rgb, color);
  }
  return color;
 }

 public static void disposeColors() {
  for (Color color : colorMap.values()) {
   color.dispose();
  }
  colorMap.clear();
 }

//-----------------------------------------
// imageMap

public static Map<String, Image> imageMap = new HashMap<String, Image>();

 protected static Image getImage(InputStream stream) throws IOException {
  try {
   Display display = Display.getCurrent();
   ImageData data = new ImageData(stream);
   if (data.transparentPixel > 0) {
    return new Image(display, data, data.getTransparencyMask());
   }
   return new Image(display, data);
  } finally {
   stream.close();
  }
 }

 public static Image getImage(String relativePathName) {//这个参数是对插件项目而言的,比如可以是:"icons/xxx.jpg"等

  //将插件项目中的 文件相对路径转换成 绝对路径的转换过程

  Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
  URL url = bundle.getResource(relativePathName);
  String fullPathString = null;
  try {
   fullPathString = FileLocator.toFileURL(url).toURI().toString();
  } catch (Exception e1) {
   e1.printStackTrace();
  }
  fullPathString = fullPathString.replaceFirst("file:/", "");
  Image image = imageMap.get(fullPathString);
  if (image == null) {
   try {
    image = getImage(new FileInputStream(fullPathString.toString()));
    imageMap.put(fullPathString, image);
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return image;
 }


 public static void disposeImages() {
  // dispose loaded images

  for (Image image : imageMap.values()) {
    image.dispose();
   }
   imageMap.clear();
  }

//-----------------------------------------
//fontMap

//...

//-----------------------------------------

//cursorsMap

//....

//------------------------------------------

/**
  * Dispose All
  */

public static void dispose() {
  disposeColors();
  disposeImages();
  //...

  //...

 }

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics