| 需求: 在浏览器中显示文件列表,每个文件前面有个图标,拖动图标到应用程序,可以直接在应用程序中打开对的文件。
环境: JDK:6.0 Develop Tools:Eclipse 3.30
备注: 图标用Applet显示,直接拖拽Applet就可以实现此功能
代码:
1 public class GragUtil extends Applet implements DropTargetListener, DragSourceListener, 2 DragGestureListener, Transferable { 3 String path; 4 DropTarget dropTarget=new DropTarget(this,this); 5 DragSource dragSource=DragSource.getDefaultDragSource(); 6 7 public String getPath() { 8 return this.path; 9 } 10 11 public void setPath(String path) { 12 this.path=path; 13 } 14 15 public GragUtil() { 16 dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE,this); 17 } 18 19 public void dragEnter(DropTargetDragEvent dropTargetDragEvent) { 20 dropTargetDragEvent.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); 21 } 22 23 public void dragExit(DropTargetEvent dropTargetEvent) { 24 // TODO Auto-generated method stub 25 26 } 27 28 public void dragOver(DropTargetDragEvent dropTargetDragEvent) { 29 // TODO Auto-generated method stub 30 31 } 32 33 public void drop(DropTargetDropEvent dropTargetDropEvent) { 34 35 } 36 37 public void dropActionChanged(DropTargetDragEvent arg0) { 38 // TODO Auto-generated method stub 39 40 } 41 42 public void dragDropEnd(DragSourceDropEvent arg0) { 43 // TODO Auto-generated method stub 44 45 } 46 47 public void dragEnter(DragSourceDragEvent arg0) { 48 // TODO Auto-generated method stub 49 50 } 51 52 public void dragExit(DragSourceEvent arg0) { 53 // TODO Auto-generated method stub 54 55 } 56 57 public void dragOver(DragSourceDragEvent arg0) { 58 // TODO Auto-generated method stub 59 60 } 61 62 public void dropActionChanged(DragSourceDragEvent arg0) { 63 // TODO Auto-generated method stub 64 65 } 66 67 public void dragGestureRecognized(DragGestureEvent dragGestureEvent) { 68 dragGestureEvent.startDrag(DragSource.DefaultCopyDrop,this,this); 69 } 70 71 public Object getTransferData(DataFlavor flavor) 72 throws UnsupportedFlavorException, IOException { 73 if(flavor==DataFlavor.javaFileListFlavor) { 74 ArrayList<File> files=new ArrayList<File>(); 75 files.add(new File(this.path)); 76 return files; 77 } 78 else { 79 throw new UnsupportedFlavorException(flavor); 80 } 81 } 82 83 public DataFlavor[] getTransferDataFlavors() { 84 return new DataFlavor[] {DataFlavor.javaFileListFlavor}; 85 } 86 87 public boolean isDataFlavorSupported(DataFlavor flavor) { 88 return flavor==DataFlavor.javaFileListFlavor; 89 } 90 91 }

|