/* * A simple Java program that demonstrates how drag and drop works * * Ben Bederson, May 3, 2002 */ import java.awt.datatransfer.*; import java.awt.dnd.*; import javax.swing.*; import javax.swing.text.*; public class DragAndDropExample extends CopyPasteExample { public DragAndDropExample() { new DragSourceExample(this); new DropTargetExample(this); } public JTextArea getTextArea() { return textArea; } public static void main(String[] args) { new DragAndDropExample(); } } class DragSourceExample implements DragGestureListener, DragSourceListener { DragAndDropExample dndexample; DragSourceExample(DragAndDropExample dndexample) { this.dndexample = dndexample; DragSource dragSource = DragSource.getDefaultDragSource(); dragSource.createDefaultDragGestureRecognizer(dndexample.getTextArea(), DnDConstants.ACTION_COPY, this); } public synchronized void dragGestureRecognized(DragGestureEvent dge) { // This is buggy because it really should only start dragging // if something is selected and you clicked on the selection - // but that is hard to do in this case since JTextArea deals with // the event handlers for you... Transferable transferable = dndexample.copy(); dge.startDrag(DragSource.DefaultCopyDrop, transferable, this); } public void dropActionChanged(DragSourceDragEvent e){} public void dragEnter(DragSourceDragEvent e) { } public void dragOver(DragSourceDragEvent dsde) { } public void dragExit(DragSourceEvent dse) { } public void dragDropEnd(DragSourceDropEvent dsde) { } } class DropTargetExample implements DropTargetListener { DragAndDropExample dndexample; DropTarget dropTarget; boolean acceptableType; DropTargetExample(DragAndDropExample dndexample) { this.dndexample = dndexample; dropTarget = new DropTarget(dndexample.getTextArea(), this); } public void dragOver(DropTargetDragEvent e) { if (!acceptableType) { e.rejectDrag(); return; } } public void dropActionChanged(DropTargetDragEvent e) { } public void dragExit(DropTargetEvent e) { } public void drop(DropTargetDropEvent e) { if (!acceptableType) { e.rejectDrop(); return; } e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); Transferable transferable = e.getTransferable(); dndexample.paste(transferable); e.dropComplete(true); } public void dragEnter(DropTargetDragEvent e) { DataFlavor[] flavors = e.getCurrentDataFlavors(); DataFlavor flavor = null; for (int i=0; i