Wednesday, September 22, 2010

GEF: Creating a connection on mouse drag

This tip shows how to implement a connection creation when dragging a mouse from EditPart, thus saving user's time (one click instead of three: activating connection creation tool, clicking on EditPart, restoring selection tool).

What you need is to return a ConnectionDragCreationTool from your EditPart:

public DragTracker getDragTracker(Request request) {
   return new ConnectionDragCreationTool();
}

The problem begins if your EditPart has a Direct Edit policy, Direct Edit commands won't be handled anymore. The following solution supports both: creating a connection on mouse drag and Direct Edit:

Create a proxy that implements DragTracker by delegating to ConnectionDragCreationTool and to SelectEditPartTracker:

public class DragConnectionCreationProxy implements DragTracker {

  private ConnectionDragCreationTool connectionTool;
  private SelectEditPartTracker editPartTracker;

  public DragConnectionCreation(EditPart editPart) {
    this.connectionTool = new ConnectionDragCreationTool();
    this.editPartTracker = new SelectEditPartTracker(editPart);
  }

  public void commitDrag() {
    connectionTool.commitDrag();
    editPartTracker.commitDrag();
  }

  // Implement all other methods ...
}

Then return this class instance from your EditPart:

public DragTracker getDragTracker(Request request) {
  return new DragConnectionCreationProxy(this);
}

1 comment:

Unknown said...

Thank you very much, this saved me a lots of walking around in the dark :D