GMF关于采用拖动方式创建连线的实例

来源:互联网 发布:java web面试题目 编辑:程序博客网 时间:2024/05/18 03:43

场景:A1 A2两个容器,分别有隔间,隔间分别容纳B1 B2两种对象,任意B1和B2之间可以单向连线(即B1-〉B2)。

问题:为了更好的用户体验,需要直接拖动A1内的B1到B2上方Drop时候,创建连线C。

解决路径:

1、A1隔间内B1可拖动,给A1隔间安装:installEditPolicy(EditPolicy.LAYOUT_ROLE, new FlowLayoutEditPolicy()....


2、A2隔间可响应拖动,给A2隔间安装:

 installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE,new DragDropEditPolicy() {protected Command getDropElementCommand(EObject element,DropObjectsRequest request) {B2EditPart ep = findB2EditPartFromPoint(request.getLocation());setDropB2EditPart(ep); //自定义方法,记录拖动到的EPif (ep == null)return null;IElementType type = XXXElementTypes.CConnection_4001;CreateRelationshipRequest req = new CreateRelationshipRequest(element, ep.resolveSemanticElement(),type);ConnectionViewAndElementDescriptor viewDescriptor = new ConnectionViewAndElementDescriptor(new CreateElementRequestAdapter(req),((IHintedType) type).getSemanticHint(),XXXDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);CreateConnectionViewAndElementRequest verequest = new CreateConnectionViewAndElementRequest(viewDescriptor);EditPart sourceEditPart = XXXBaseItemSemanticEditPolicy.getDiagramEditPart(getHost()).findEditPart(null, element); // create the subtopics link command ICommand createSubTopicsCmd = new DeferredCreateConnectionViewAndElementCommand(verequest, new EObjectAdapter((EObject) sourceEditPart.getModel()), new EObjectAdapter(ep.getPrimaryView()), getHost().getViewer()); return new ICommandProxy(createSubTopicsCmd);}});


 

 

 

        //根据拖动的位置找B2的方法private B2EditPart findB2EditPartFromPoint(Point pt) {EditPart ep = this.getRoot().getViewer().findObjectAt(pt);if (ep instanceof B2EditPart)return (B2EditPart) ep;else if (ep.getParent() instanceof AttributeEditPart) {return (B2) ep.getParent();}return null;}


3、A2隔间的A2CompartmentItemSemanticEditPolicy中,响应创建元素Request

 

protected Command getCreateCommand(CreateElementRequest req) {                //.........以上为自动生成代码if (XXXElementTypes.CConnection_4001 == req.getElementType()) {EObject target = null;if (getHost() instanceof A2CompartmentEditPart) {A2CompartmentEditPart) part = (B2CompartmentEditPart) getHost();B2EditPart ep = part.getDropB2EditPart();if (ep != null)target = ep.resolveSemanticElement();elsereturn null;CreateRelationshipRequest req1 = new CreateRelationshipRequest(req.getNewElement(), target, req.getElementType());B2ItemSemanticEditPolicy poc = (B2ItemSemanticEditPolicy) ep.getEditPolicy(EditPolicyRoles.SEMANTIC_ROLE);Command cmd1 = poc.getCompleteCreateRelationshipCommand(req1); //此方法最终传导到了XXXBaseItemSemanticEditPolicyreturn cmd1;}}return super.getCreateCommand(req);}


 

 

4、XXXBaseItemSemanticEditPolicy中完成getCreateRelationshipCommand

protected Command getCreateRelationshipCommand(CreateRelationshipRequest req) {if (req.getSource()!=null&&req.getTarget()!=null){CConnectionCreateCommand cmd = new CConnectionCreateCommand(req,req.getSource(), req.getTarget());return new ICommandProxy(cmd);}return null;}