Monday, May 20, 2013

GWT: Drag and Drop Event

The client.Element GWT class has a method called 'setDraggable', what do exactly what its name says: It mark an object as draggable. Let's check how it works out exactly.

In GWT (Google Web Toolkit), if you have a component that extends from client.Element, for sure it has the setDraggable method to say the system that it can be dragged through the screen.

That's quite simple. However we'll need to catch that object in another place (by another event) and change both by each other.

For sure we'll need to have a copy of the dragging object to work on it afterward.

For that example, let's suppose that we're building a table what has its cells represented as a MyCell object what extends client.Element. Let's see the following lines:
private MyCell draggingCell = null;
private MyCell targetCell = null;
protected void setAsDraggable(final MyCell cell){
  cell.getElement().setDraggable(Element.DRAGGABLE_TRUE);

  cell.addDomHandler(new DragStartHandler() {
   @Override
   public void onDragStart(final DragStartEvent event) {
    //this line is necessary for that the event works on Firefox!
    event.setData("text", "drag started!");
    draggingCell = (MyCell)event.getSource();
   }
  }, DragStartEvent.getType());
 }

protected void setCatchDrag(final MyCell cell){
  cell.addDomHandler(new DragOverHandler() {
   @Override
   public void onDragOver(final DragOverEvent event) {
   }
  }, DragOverEvent.getType());

  cell.addDomHandler(new DropHandler() {
   @Override
   public void onDrop(final DropEvent event) {
    event.preventDefault();
    targetCell = (MyCell)event.getSource();
    changeContexts(draggingCell, targetCell);
   }
  }, DropEvent.getType());
 }

protected void changeContexts(MyCell from, MyCell to){
  MyCell aux = to;
  to = from;
  from = aux;
}

At the onDragStart handler, I just save a copy of the dragging object and after, when then user drop the object and the onDrop event is dispatched it's time to save the target object and call the changeContexts method to do it's properly change the object's place and so, we could have the drag and drop effect as well.

Note that I've written two principal methods setAsDraggable and setCatchDrag what must be call to every cell that we want to turn draggable and catchable respectively.

No comments:

Post a Comment