About

Drag and Drop using GWT

Drag and drop can be an important feature in web apps. It allows adding a human touch to UIs. Drag and drag can be easily implemented using Html5 and Javascript, and also using other frameworks such as jquery. For Java web development, GWT provides a good solution. GWT have added a native feature to enable drag and drop for widgets and components. We are going to walk through it in this tutorial.

As the name implies, drag and drop has two sides: the element to be dragged, and the element to be dropped on.

To enable drag for any widget or component in GWT, we have to use the addDragHandler method. For example:


Image image = new Image("images/car.png");
image.addDragStartHandler(new DragStartHandler(){
   @Override
 public void onDragStart(DragStartEvent event) {
       // required: data to be transferred to the drop handler
              event.setData("text", image.getElement().getInnerHTML()); 
   }});

Not all elements have the addDragHandler by default. If an element is not implementing the DragHandler interface, the developper needs to add the handler to the DOM handlers:

        

image.addDomHandler(new DragStartHandler(){
     @Override
     public void onDragStart(DragStartEvent event) {
         // required: data to be transferred to the drop handler
   event.setData("text", image.getElement().getInnerHTML());
    }}, DragStartEvent.getType());

For the drop, we need to implement two handlers: DropHandler and DragOverHandler.

Suppose we want to use a FlowPanel as a drop target:

          

FlowPanel target = new FlowPanel();

target.addDomHandler(new DragOverHandler() {
           @Override
           public void onDragOver(DragOverEvent event) {
               //Do something like changing background
       }
   }, DragOverEvent.getType());
   
    target.addDomHandler(new DropHandler() {
      @Override
      public void onDrop(DropEvent event) {
          // required
       event.preventDefault();
        
          // get the data out of the event
          String data = event.getData("text");
          Image image = new Image(data);
   
      }
  }, DropEvent.getType());

That’s it. Now we can drag the Image into the FlowPanel.

There are other GWT libraries that implements Drag and Drop out of the box such as: 
It is advised for developpers to roll their own drag and drop in order not to depend on any implementation. 

Archive

Subscribe

Atom

Blog Partners