默认情况下,GEF中要创建一个新的结点都是通点在Palette上选择一个结点,然后在Editor区域单击实现的。
也有一些是通过拖放Palette中的一个对象到Editor区域来实现的。
要实现一个拖放支持也是很容易的。GEF中默认实现了一组drag-drop listener用来支持拖放实现:
1。TemplateTransferDropTargetListener
因为是要从palette上拖到Editor中,所以此监听事件显示是应该安放在Editor上,在GEF中就是GraphicalViewer,可以在initializeGraphicalViewer()方法中加上:
getGraphicalViewer().addDropTargetListener(new TemplateTransferDropTargetListener(
getGraphicalViewer()));
2。TemplateTransferDragSourceListener
显示此事件需要加在palette上,也就是PaletteViewer上,可以在initializePaletteViewer()方法中加上:
getPaletteViewer().addDragSourceListener(new TemplateTransferDragSourceListener(getPaletteViewer()));
回头再看一下我们对Palette上的Item的声明:
CombinedTemplateCreationEntry(String label, String shortDesc,
CreationFactory factory, ImageDescriptor iconSmall, ImageDescriptor iconLarge)
需要注意CombinedTemplateCreationEntry构造方法的选用。认为上述构造方法为默认选择,而CreationFactory类为SimpleFactory。
如果选择另一个构造方法:
CombinedTemplateCreationEntry(String label, String shortDesc, Object template,
CreationFactory factory, ImageDescriptor iconSmall, ImageDescriptor iconLarge)
则我们需要注意:如果template和factory都是SimpleFactory则没有问题,因为默认的template就是SimpleFactory。否则我们需要根据自己的template值来得到对应的model,也就是要实现自己的CreationFactory。例如:
CombinedTemplateCreationEntry elementCreationEntry = new CombinedTemplateCreationEntry( "Element", "Element type",ModelCreationFactory.ELEMENT_TYPE,new ModelCreationFactory(ModelCreationFactory.ELEMENT_TYPE), Activator .getImageDescriptor("icons/element.png"), Activator .getImageDescriptor("icons/element.png")); CombinedTemplateCreationEntry attributeCreationEntry = new CombinedTemplateCreationEntry( "Attribute", "Attribute type",ModelCreationFactory.ATTRIBUTE_TYPE, new ModelCreationFactory(ModelCreationFactory.ATTRIBUTE_TYPE), Activator .getImageDescriptor("icons/attribute.png"), Activator .getImageDescriptor("icons/attribute.png"));
getGraphicalViewer().addDropTargetListener(new CustomTemplateTransferDropTargetListener( getGraphicalViewer()));
public class ModelCreationFactory implements CreationFactory { private int objectType; public static final int ELEMENT_TYPE = 0x01; public static final int ATTRIBUTE_TYPE = 0x02; public static final int ROOT_TYPE = 0x04; public ModelCreationFactory(int objectType) { super(); this.objectType = objectType; } public Object getNewObject() { switch (objectType) { case ELEMENT_TYPE: return new ElementType(); case ATTRIBUTE_TYPE: return new AttributeType(); case ROOT_TYPE: return new RootType(); default: break; } return null; } public Object getObjectType() { return objectType; } }
public class CustomTemplateTransferDropTargetListener extends TemplateTransferDropTargetListener { public CustomTemplateTransferDropTargetListener(EditPartViewer viewer) { super(viewer); } @Override protected CreationFactory getFactory(Object template) { return new ModelCreationFactory(((Integer)template).intValue()); } }