Drag & Drop for the tree

In the example application, you can drag a user entry (a leaf in the tree view) to another group (a node in the tree view), thereby changing the data in the model (of course changes must be saved by pressing the 'Save' button or selecting the item 'Save' from the 'File' menu).

This feature is implemented in a command that is initialized in the MainForm. As you would expect, that command is called PerformDragDrop, and resides, along with all other commands, in the gui.commands package.

For Drag & Drop, there is a special event listener which can be added to trees. As usual with event listeners, it can be implemented as anonymous class, and then be added to the TreeViewer via the addDragDropListener( DragDropListener ) method. After this is done, all nodes on the tree fire a DragDropEvent whenever the user attempts to drag some other element of the same tree onto one of them.

Here is the implementation of the actual Drag & Drop in the PerformDragDrop command:

    Object source = treeViewer.getElement( dragSource );
    Object dest = treeViewer.getElement( dragDestination ); 
    // we allow only dragging a user to a group
    if( source instanceof User && dest instanceof Group ) {
      // find out to which group the source belongs
      TreeNode oldParent = ( TreeNode )dragSource.getParentNode();

      // determine the affected data objects
      Group oldGroup = ( Group )treeViewer.getElement( oldParent );
      Group newGroup = ( Group )dest;
      User user = ( User )source;

For the Drag & Drop support it is necessary to get information out of the tree items which are involved in the event. We must know which User or Group object they represent, so we ask the TreeViewer for their data elements. This is the reason for keeping a reference to the TreeViewer instance in this command object.

Once we have the data objects, we ask the model to perform the changes to the data (that's the job of the business logic, not the ui):

      if( oldGroup != newGroup ) {
        // update the Model
        Model.getInstance().moveUser( user, oldGroup, newGroup );

Finally, we call another command that changes the state of the ui to 'dirty': we remind the user to save by use of the SetChanged command:

        // notify the rest of the ui
        Object[] changeParams = new Object[] { Boolean.TRUE };
        Command cmd = W4TContext.findCommand( Constants.CMD_SET_CHANGED );
        cmd.process( changeParams );

Copyright (c) 2003 by Innoopract Informationssysteme GmbH. All rights reserved.