Implementing drag and drop

Drag and drop more or less is cut and paste without having to use the menu. As SimplyHTML has implemented cut and paste for styled text and HTML text in stage 2, it has the basis for drag and drop too.

Typical drag an drop

A typical drag and drop operation in the editor would act as follows: By selecting text in the editor and by dragging the selection with the mouse, a copy operation is initiated. Once the selection is dropped anywhere else in the editor, the selection is removed from the original location and pasted at the new location.

To implement drag and drop a mechanism has to be implemented to recognize drag and drop activities and to react in the described way.

The Java Tutorial

There is a good example about how to implement drag and drop in The Java Tutorial. The drag and drop example is well explained there already. At this point therefore only some more general aspects are discussed only.

The Java Tutorial is available online at http://java.sun.com/docs/books/tutorial/

Note: In J2SE 1.4 the original drag and drop is simplified by wrapping the 'old' implementation into class TransferHandler partly but as SimplyHTML shall be available to users of the 1.3 Runtime, the 'old' mechanism is implemented which in fact does the same as the 'new' one.

Drag and drop in SimplyHTML

Class SHTMLEditorPane has been created in this stage to allow for own cut and paste handling. For drag and drop support it has an additional section in the source code. The main parts of the drag and drop implementation are methods

- initDnd
- dragGestureRecognized
- drop and
- doDrop

Method initDnd

Method initDnd instantiates the objects necessary to control our drag and drop implementation: DragSource and DropTarget. The SHTMLEditorPane registers itself as a DropTarget and as a DropTargetListener. In DragSource SHTMLEditPane registers itself as a DragGestureRecognizer. As well it registers as a MouseListener to keep track of the selection during drag and drop operations.

Method dragGestureRecognized

dragGestureRecognized is the method SHTMLEditorPane has to implement to be a DragGestureRecognizer. The method is invoked by all drag initiating gestures on SHTMLEditorPane.

In method dragGestureRecognized an HTMLText object is created on the currently selected text and an HTMLTextSelection transferable is created wrapping the HTMLText object. Finally the drag operation is initiated by invoking method DragSource.startDrag with the newly created transferable.

Method drop

Once a drop event is recognized, method drop is invoked. In SimplyHTML it calls method doDrop if a suitable DataFlavor (HTMLText or String) is found in the dragged element. Otherwise the drop is rejected.

Method doDrop

Method doDrop does the actual cut and paste resulting from the drag and drop operation consisting of adding the dragged element and necessarily removing the dragged element from the original position.