public class MyTree implements DragGestureListener, DropTargetListener, DragSourceListener{ /** Variables needed for DnD */ private DragSource dragSource = null; /** Some drag objects */ private DropTarget dropTarget = null; /** Tree node data which was draged */ private TreeNodeData dragNode; public MyTree(){ dragSource = DragSource.getDefaultDragSource(); DragGestureRecognizer dgr = dragSource.createDefaultDragGestureRecognizer(this, // DragSource DnDConstants.ACTION_COPY_OR_MOVE, // specifies valid // actions this // DragGestureListener ); /* * Eliminates right mouse clicks as valid actions - useful especially if * you implement a JPopupMenu for the JTree */ dgr.setSourceActions(dgr.getSourceActions() & ~InputEvent.BUTTON3_MASK); } public void dragGestureRecognized(DragGestureEvent e) { dropTarget = new DropTarget(MyList, this); dragNode = (TreeNodeData) getSelectedNode().getUserObject(); if (dragNode != null) { Transferable transferable = dragNode; } // Select the appropriate cursor; Cursor cursor = DragSource.DefaultCopyNoDrop; int action = e.getDragAction(); if (action == DnDConstants.ACTION_MOVE) cursor = DragSource.DefaultMoveNoDrop;
// Begin drag dragSource.startDrag(e, cursor, transferable, this); } /** DropTargetListener interface method - What we do when drag is released */ public void drop(DropTargetDropEvent e) { DropTarget dropTargetTmp = e.getDropTargetContext().getDropTarget(); Object transferData = null;
/** Variables needed for DnD */
private DragSource dragSource = null; /** Some drag objects */
private DropTarget dropTarget = null; /** Tree node data which was draged */
private TreeNodeData dragNode; public MyTree(){
dragSource = DragSource.getDefaultDragSource();
DragGestureRecognizer dgr = dragSource.createDefaultDragGestureRecognizer(this, // DragSource
DnDConstants.ACTION_COPY_OR_MOVE, // specifies valid
// actions
this // DragGestureListener
);
/*
* Eliminates right mouse clicks as valid actions - useful especially if
* you implement a JPopupMenu for the JTree
*/
dgr.setSourceActions(dgr.getSourceActions() & ~InputEvent.BUTTON3_MASK);
} public void dragGestureRecognized(DragGestureEvent e) {
dropTarget = new DropTarget(MyList, this);
dragNode = (TreeNodeData) getSelectedNode().getUserObject(); if (dragNode != null) {
Transferable transferable = dragNode;
}
// Select the appropriate cursor;
Cursor cursor = DragSource.DefaultCopyNoDrop;
int action = e.getDragAction();
if (action == DnDConstants.ACTION_MOVE)
cursor = DragSource.DefaultMoveNoDrop;
// Begin drag
dragSource.startDrag(e, cursor, transferable, this);
}
/** DropTargetListener interface method - What we do when drag is released */
public void drop(DropTargetDropEvent e) { DropTarget dropTargetTmp = e.getDropTargetContext().getDropTarget();
Object transferData = null;
if(dropTargetTmp.equals(dropTarget)){
System.out.println("got it!");
}}
还有其他一些事件接口